blob: d280523cd7cb1d9b7246d508f59f424234885e1a [file] [log] [blame]
James Kuszmaul61750662021-06-21 21:32:33 -07001#include "y2020/control_loops/drivetrain/localizer.h"
2
James Kuszmaul5398fae2020-02-17 16:44:03 -08003#include <queue>
4
Austin Schuhb06f03b2021-02-17 22:00:37 -08005#include "aos/events/logging/log_writer.h"
James Kuszmaul958b21e2020-02-26 21:51:40 -08006#include "aos/network/message_bridge_server_generated.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -08007#include "aos/network/team_number.h"
James Kuszmaul61750662021-06-21 21:32:33 -07008#include "frc971/control_loops/control_loop_test.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -08009#include "frc971/control_loops/drivetrain/drivetrain.h"
10#include "frc971/control_loops/drivetrain/drivetrain_test_lib.h"
11#include "frc971/control_loops/team_number_test_environment.h"
James Kuszmaul61750662021-06-21 21:32:33 -070012#include "gtest/gtest.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -080013#include "y2020/control_loops/drivetrain/drivetrain_base.h"
James Kuszmaul688a2b02020-02-19 18:26:33 -080014#include "y2020/control_loops/superstructure/superstructure_status_generated.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -080015
16DEFINE_string(output_file, "",
17 "If set, logs all channels to the provided logfile.");
James Kuszmaul2971b5a2023-01-29 15:49:32 -080018DECLARE_bool(die_on_malloc);
James Kuszmaul5398fae2020-02-17 16:44:03 -080019
20// This file tests that the full 2020 localizer behaves sanely.
21
22namespace y2020 {
23namespace control_loops {
24namespace drivetrain {
25namespace testing {
26
Austin Schuh66168842021-08-17 19:42:21 -070027using aos::logger::BootTimestamp;
James Kuszmaul5398fae2020-02-17 16:44:03 -080028using frc971::control_loops::drivetrain::DrivetrainConfig;
29using frc971::control_loops::drivetrain::Goal;
30using frc971::control_loops::drivetrain::LocalizerControl;
Brian Silverman1f345222020-09-24 21:14:48 -070031using frc971::vision::sift::CameraCalibrationT;
32using frc971::vision::sift::CameraPoseT;
James Kuszmaul5398fae2020-02-17 16:44:03 -080033using frc971::vision::sift::ImageMatchResult;
34using frc971::vision::sift::ImageMatchResultT;
James Kuszmaul5398fae2020-02-17 16:44:03 -080035using frc971::vision::sift::TransformationMatrixT;
36
37namespace {
38DrivetrainConfig<double> GetTest2020DrivetrainConfig() {
39 DrivetrainConfig<double> config = GetDrivetrainConfig();
40 return config;
41}
42
43// Copies an Eigen matrix into a row-major vector of the data.
44std::vector<float> MatrixToVector(const Eigen::Matrix<double, 4, 4> &H) {
45 std::vector<float> data;
46 for (int row = 0; row < 4; ++row) {
47 for (int col = 0; col < 4; ++col) {
48 data.push_back(H(row, col));
49 }
50 }
51 return data;
52}
53
54// Provides the location of the turret to use for simulation. Mostly we care
55// about providing a location that is not perfectly aligned with the robot's
56// origin.
57Eigen::Matrix<double, 4, 4> TurretRobotTransformation() {
58 Eigen::Matrix<double, 4, 4> H;
59 H.setIdentity();
James Kuszmaul688a2b02020-02-19 18:26:33 -080060 H.block<3, 1>(0, 3) << 1, 1.1, 0.9;
James Kuszmaul5398fae2020-02-17 16:44:03 -080061 return H;
62}
63
64// Provides the location of the camera on the turret.
65// TODO(james): Also simulate a fixed camera that is *not* on the turret.
66Eigen::Matrix<double, 4, 4> CameraTurretTransformation() {
67 Eigen::Matrix<double, 4, 4> H;
68 H.setIdentity();
69 H.block<3, 1>(0, 3) << 0.1, 0, 0;
70 // Introduce a bit of pitch to make sure that we're exercising all the code.
71 H.block<3, 3>(0, 0) =
James Kuszmaul688a2b02020-02-19 18:26:33 -080072 Eigen::AngleAxis<double>(0.1, Eigen::Vector3d::UnitY()) *
James Kuszmaul5398fae2020-02-17 16:44:03 -080073 H.block<3, 3>(0, 0);
74 return H;
75}
76
77// The absolute target location to use. Not meant to correspond with a
78// particular field target.
79// TODO(james): Make more targets.
James Kuszmaul688a2b02020-02-19 18:26:33 -080080std::vector<Eigen::Matrix<double, 4, 4>> TargetLocations() {
81 std::vector<Eigen::Matrix<double, 4, 4>> locations;
James Kuszmaul5398fae2020-02-17 16:44:03 -080082 Eigen::Matrix<double, 4, 4> H;
83 H.setIdentity();
84 H.block<3, 1>(0, 3) << 10.0, 0, 0;
James Kuszmaul688a2b02020-02-19 18:26:33 -080085 locations.push_back(H);
86 H.block<3, 1>(0, 3) << -10.0, 0, 0;
James Kuszmaul5a46c8d2021-09-03 19:33:48 -070087 H.block<3, 3>(0, 0) =
88 Eigen::AngleAxis<double>(1.1, Eigen::Vector3d::UnitZ()) *
89 H.block<3, 3>(0, 0);
James Kuszmaul688a2b02020-02-19 18:26:33 -080090 locations.push_back(H);
91 return locations;
James Kuszmaul5398fae2020-02-17 16:44:03 -080092}
James Kuszmaul958b21e2020-02-26 21:51:40 -080093
James Kuszmaul8866e642022-06-10 16:00:36 -070094constexpr std::chrono::seconds kPiTimeOffset(10);
James Kuszmaul5398fae2020-02-17 16:44:03 -080095} // namespace
96
97namespace chrono = std::chrono;
James Kuszmaul5398fae2020-02-17 16:44:03 -080098using aos::monotonic_clock;
Brian Silverman1f345222020-09-24 21:14:48 -070099using frc971::control_loops::drivetrain::DrivetrainLoop;
100using frc971::control_loops::drivetrain::testing::DrivetrainSimulation;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800101
James Kuszmaul61750662021-06-21 21:32:33 -0700102class LocalizedDrivetrainTest : public frc971::testing::ControlLoopTest {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800103 protected:
104 // We must use the 2020 drivetrain config so that we don't have to deal
105 // with shifting:
106 LocalizedDrivetrainTest()
James Kuszmaul61750662021-06-21 21:32:33 -0700107 : frc971::testing::ControlLoopTest(
James Kuszmaul5398fae2020-02-17 16:44:03 -0800108 aos::configuration::ReadConfig(
109 "y2020/control_loops/drivetrain/simulation_config.json"),
Austin Schuh0debde12022-08-17 16:25:17 -0700110 GetTest2020DrivetrainConfig().dt,
111 {{BootTimestamp::epoch() + kPiTimeOffset,
112 BootTimestamp::epoch() + kPiTimeOffset,
113 BootTimestamp::epoch() + kPiTimeOffset,
114 BootTimestamp::epoch() + kPiTimeOffset,
115 BootTimestamp::epoch() + kPiTimeOffset,
116 BootTimestamp::epoch() + kPiTimeOffset, BootTimestamp::epoch()}}),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800117 roborio_(aos::configuration::GetNode(configuration(), "roborio")),
118 pi1_(aos::configuration::GetNode(configuration(), "pi1")),
119 test_event_loop_(MakeEventLoop("test", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800120 drivetrain_goal_sender_(
121 test_event_loop_->MakeSender<Goal>("/drivetrain")),
122 drivetrain_goal_fetcher_(
123 test_event_loop_->MakeFetcher<Goal>("/drivetrain")),
James Kuszmaul0a981402021-10-09 21:00:34 -0700124 drivetrain_status_fetcher_(
125 test_event_loop_
126 ->MakeFetcher<frc971::control_loops::drivetrain::Status>(
127 "/drivetrain")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800128 localizer_control_sender_(
129 test_event_loop_->MakeSender<LocalizerControl>("/drivetrain")),
James Kuszmaul688a2b02020-02-19 18:26:33 -0800130 superstructure_status_sender_(
131 test_event_loop_->MakeSender<superstructure::Status>(
132 "/superstructure")),
James Kuszmaul958b21e2020-02-26 21:51:40 -0800133 server_statistics_sender_(
134 test_event_loop_->MakeSender<aos::message_bridge::ServerStatistics>(
135 "/aos")),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800136 drivetrain_event_loop_(MakeEventLoop("drivetrain", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800137 dt_config_(GetTest2020DrivetrainConfig()),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800138 pi1_event_loop_(MakeEventLoop("test", pi1_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800139 camera_sender_(
Austin Schuh6aa77be2020-02-22 21:06:40 -0800140 pi1_event_loop_->MakeSender<ImageMatchResult>("/pi1/camera")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800141 localizer_(drivetrain_event_loop_.get(), dt_config_),
142 drivetrain_(dt_config_, drivetrain_event_loop_.get(), &localizer_),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800143 drivetrain_plant_event_loop_(MakeEventLoop("plant", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800144 drivetrain_plant_(drivetrain_plant_event_loop_.get(), dt_config_),
145 last_frame_(monotonic_now()) {
James Kuszmaul9c128122021-03-22 22:24:36 -0700146 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), roborio_), 6);
Austin Schuh87dd3832021-01-01 23:07:31 -0800147 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), pi1_), 1);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800148 set_team_id(frc971::control_loops::testing::kTeamNumber);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800149 set_battery_voltage(12.0);
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800150 FLAGS_die_on_malloc = true;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800151
152 if (!FLAGS_output_file.empty()) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800153 logger_event_loop_ = MakeEventLoop("logger", roborio_);
Brian Silverman1f345222020-09-24 21:14:48 -0700154 logger_ = std::make_unique<aos::logger::Logger>(logger_event_loop_.get());
James Kuszmaul0a981402021-10-09 21:00:34 -0700155 logger_->StartLoggingOnRun(FLAGS_output_file);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800156 }
157
158 test_event_loop_->MakeWatcher(
159 "/drivetrain",
160 [this](const frc971::control_loops::drivetrain::Status &) {
161 // Needs to do camera updates right after we run the control loop.
162 if (enable_cameras_) {
163 SendDelayedFrames();
164 if (last_frame_ + std::chrono::milliseconds(100) <
165 monotonic_now()) {
166 CaptureFrames();
167 last_frame_ = monotonic_now();
168 }
169 }
Brian Silverman1f345222020-09-24 21:14:48 -0700170 });
James Kuszmaul688a2b02020-02-19 18:26:33 -0800171
172 test_event_loop_->AddPhasedLoop(
173 [this](int) {
James Kuszmaul0a981402021-10-09 21:00:34 -0700174 // TODO(james): This is wrong. At a bare minimum, it is missing a boot
175 // UUID, and this is probably the wrong pattern entirely.
James Kuszmaul958b21e2020-02-26 21:51:40 -0800176 auto builder = server_statistics_sender_.MakeBuilder();
177 auto name_offset = builder.fbb()->CreateString("pi1");
178 auto node_builder = builder.MakeBuilder<aos::Node>();
179 node_builder.add_name(name_offset);
180 auto node_offset = node_builder.Finish();
181 auto connection_builder =
182 builder.MakeBuilder<aos::message_bridge::ServerConnection>();
183 connection_builder.add_node(node_offset);
184 connection_builder.add_monotonic_offset(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700185 chrono::duration_cast<chrono::nanoseconds>(kPiTimeOffset)
James Kuszmaul958b21e2020-02-26 21:51:40 -0800186 .count());
187 auto connection_offset = connection_builder.Finish();
188 auto connections_offset =
189 builder.fbb()->CreateVector(&connection_offset, 1);
190 auto statistics_builder =
191 builder.MakeBuilder<aos::message_bridge::ServerStatistics>();
192 statistics_builder.add_connections(connections_offset);
milind1f1dca32021-07-03 13:50:07 -0700193 CHECK_EQ(builder.Send(statistics_builder.Finish()),
194 aos::RawSender::Error::kOk);
James Kuszmaul958b21e2020-02-26 21:51:40 -0800195 },
196 chrono::milliseconds(500));
197
198 test_event_loop_->AddPhasedLoop(
199 [this](int) {
James Kuszmaul688a2b02020-02-19 18:26:33 -0800200 // Also use the opportunity to send out turret messages.
201 UpdateTurretPosition();
202 auto builder = superstructure_status_sender_.MakeBuilder();
203 auto turret_builder =
204 builder
205 .MakeBuilder<frc971::control_loops::
206 PotAndAbsoluteEncoderProfiledJointStatus>();
207 turret_builder.add_position(turret_position_);
208 turret_builder.add_velocity(turret_velocity_);
209 auto turret_offset = turret_builder.Finish();
210 auto status_builder = builder.MakeBuilder<superstructure::Status>();
211 status_builder.add_turret(turret_offset);
milind1f1dca32021-07-03 13:50:07 -0700212 CHECK_EQ(builder.Send(status_builder.Finish()),
213 aos::RawSender::Error::kOk);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800214 },
Yash Chainania6fe97b2021-12-15 21:01:11 -0800215 frc971::controls::kLoopFrequency);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800216
James Kuszmaul286b4282020-02-26 20:29:32 -0800217 test_event_loop_->OnRun([this]() { SetStartingPosition({3.0, 2.0, 0.0}); });
218
James Kuszmaul5398fae2020-02-17 16:44:03 -0800219 // Run for enough time to allow the gyro/imu zeroing code to run.
James Kuszmaul0a981402021-10-09 21:00:34 -0700220 RunFor(std::chrono::seconds(15));
221 CHECK(drivetrain_status_fetcher_.Fetch());
222 EXPECT_TRUE(CHECK_NOTNULL(drivetrain_status_fetcher_->zeroing())->zeroed());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800223 }
224
225 virtual ~LocalizedDrivetrainTest() override {}
226
227 void SetStartingPosition(const Eigen::Matrix<double, 3, 1> &xytheta) {
228 *drivetrain_plant_.mutable_state() << xytheta.x(), xytheta.y(),
229 xytheta(2, 0), 0.0, 0.0;
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700230 Eigen::Matrix<double, Localizer::HybridEkf::kNStates, 1> localizer_state;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800231 localizer_state.setZero();
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700232 localizer_state.block<3, 1>(0, 0) = xytheta;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800233 localizer_.Reset(monotonic_now(), localizer_state);
234 }
235
James Kuszmaul0a981402021-10-09 21:00:34 -0700236 void VerifyNearGoal(double eps = 1e-2) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800237 drivetrain_goal_fetcher_.Fetch();
238 EXPECT_NEAR(drivetrain_goal_fetcher_->left_goal(),
239 drivetrain_plant_.GetLeftPosition(), eps);
240 EXPECT_NEAR(drivetrain_goal_fetcher_->right_goal(),
241 drivetrain_plant_.GetRightPosition(), eps);
242 }
243
James Kuszmaul688a2b02020-02-19 18:26:33 -0800244 ::testing::AssertionResult IsNear(double expected, double actual,
245 double epsilon) {
246 if (std::abs(expected - actual) < epsilon) {
247 return ::testing::AssertionSuccess();
248 } else {
249 return ::testing::AssertionFailure()
250 << "Expected " << expected << " but got " << actual
251 << " with a max difference of " << epsilon
252 << " and an actual difference of " << std::abs(expected - actual);
253 }
254 }
255 ::testing::AssertionResult VerifyEstimatorAccurate(double eps) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800256 const Eigen::Matrix<double, 5, 1> true_state = drivetrain_plant_.state();
James Kuszmaul688a2b02020-02-19 18:26:33 -0800257 ::testing::AssertionResult result(true);
258 if (!(result = IsNear(localizer_.x(), true_state(0), eps))) {
259 return result;
260 }
261 if (!(result = IsNear(localizer_.y(), true_state(1), eps))) {
262 return result;
263 }
264 if (!(result = IsNear(localizer_.theta(), true_state(2), eps))) {
265 return result;
266 }
267 if (!(result = IsNear(localizer_.left_velocity(), true_state(3), eps))) {
268 return result;
269 }
270 if (!(result = IsNear(localizer_.right_velocity(), true_state(4), eps))) {
271 return result;
272 }
273 return result;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800274 }
275
276 // Goes through and captures frames on the camera(s), queueing them up to be
277 // sent by SendDelayedFrames().
278 void CaptureFrames() {
279 const frc971::control_loops::Pose robot_pose(
280 {drivetrain_plant_.GetPosition().x(),
281 drivetrain_plant_.GetPosition().y(), 0.0},
282 drivetrain_plant_.state()(2, 0));
283 std::unique_ptr<ImageMatchResultT> frame(new ImageMatchResultT());
284
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800285 for (const auto &H_field_target : TargetLocations()) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800286 std::unique_ptr<CameraPoseT> camera_target(new CameraPoseT());
287
288 camera_target->field_to_target.reset(new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800289 camera_target->field_to_target->data = MatrixToVector(H_field_target);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800290
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800291 Eigen::Matrix<double, 4, 4> H_turret_camera =
James Kuszmaul688a2b02020-02-19 18:26:33 -0800292 Eigen::Matrix<double, 4, 4>::Identity();
293 if (is_turreted_) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800294 H_turret_camera = frc971::control_loops::TransformationMatrixForYaw(
James Kuszmaul688a2b02020-02-19 18:26:33 -0800295 turret_position_) *
296 CameraTurretTransformation();
297 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800298
299 // TODO(james): Use non-zero turret angles.
300 camera_target->camera_to_target.reset(new TransformationMatrixT());
James Kuszmaulaca88782021-04-24 16:48:45 -0700301 camera_target->camera_to_target->data = MatrixToVector(
302 (robot_pose.AsTransformationMatrix() * TurretRobotTransformation() *
303 H_turret_camera * camera_calibration_offset_)
304 .inverse() *
305 H_field_target);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800306
307 frame->camera_poses.emplace_back(std::move(camera_target));
308 }
309
310 frame->image_monotonic_timestamp_ns =
311 chrono::duration_cast<chrono::nanoseconds>(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800312 event_loop_factory()
313 ->GetNodeEventLoopFactory(pi1_)
314 ->monotonic_now()
315 .time_since_epoch())
James Kuszmaul5398fae2020-02-17 16:44:03 -0800316 .count();
317 frame->camera_calibration.reset(new CameraCalibrationT());
318 {
319 frame->camera_calibration->fixed_extrinsics.reset(
320 new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800321 TransformationMatrixT *H_robot_turret =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800322 frame->camera_calibration->fixed_extrinsics.get();
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800323 H_robot_turret->data = MatrixToVector(TurretRobotTransformation());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800324 }
James Kuszmaul688a2b02020-02-19 18:26:33 -0800325
326 if (is_turreted_) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800327 frame->camera_calibration->turret_extrinsics.reset(
328 new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800329 TransformationMatrixT *H_turret_camera =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800330 frame->camera_calibration->turret_extrinsics.get();
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800331 H_turret_camera->data = MatrixToVector(CameraTurretTransformation());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800332 }
333
334 camera_delay_queue_.emplace(monotonic_now(), std::move(frame));
335 }
336
337 // Actually sends out all the camera frames.
338 void SendDelayedFrames() {
339 const std::chrono::milliseconds camera_latency(150);
340 while (!camera_delay_queue_.empty() &&
341 std::get<0>(camera_delay_queue_.front()) <
342 monotonic_now() - camera_latency) {
343 auto builder = camera_sender_.MakeBuilder();
milind1f1dca32021-07-03 13:50:07 -0700344 ASSERT_EQ(
345 builder.Send(ImageMatchResult::Pack(
346 *builder.fbb(), std::get<1>(camera_delay_queue_.front()).get())),
347 aos::RawSender::Error::kOk);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800348 camera_delay_queue_.pop();
349 }
350 }
351
Austin Schuh6aa77be2020-02-22 21:06:40 -0800352 const aos::Node *const roborio_;
353 const aos::Node *const pi1_;
354
James Kuszmaul5398fae2020-02-17 16:44:03 -0800355 std::unique_ptr<aos::EventLoop> test_event_loop_;
356 aos::Sender<Goal> drivetrain_goal_sender_;
357 aos::Fetcher<Goal> drivetrain_goal_fetcher_;
James Kuszmaul0a981402021-10-09 21:00:34 -0700358 aos::Fetcher<frc971::control_loops::drivetrain::Status>
359 drivetrain_status_fetcher_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800360 aos::Sender<LocalizerControl> localizer_control_sender_;
James Kuszmaul688a2b02020-02-19 18:26:33 -0800361 aos::Sender<superstructure::Status> superstructure_status_sender_;
James Kuszmaul958b21e2020-02-26 21:51:40 -0800362 aos::Sender<aos::message_bridge::ServerStatistics> server_statistics_sender_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800363
364 std::unique_ptr<aos::EventLoop> drivetrain_event_loop_;
Brian Silverman1f345222020-09-24 21:14:48 -0700365 const frc971::control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800366
Austin Schuh6aa77be2020-02-22 21:06:40 -0800367 std::unique_ptr<aos::EventLoop> pi1_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800368 aos::Sender<ImageMatchResult> camera_sender_;
369
370 Localizer localizer_;
371 DrivetrainLoop drivetrain_;
372
373 std::unique_ptr<aos::EventLoop> drivetrain_plant_event_loop_;
374 DrivetrainSimulation drivetrain_plant_;
375 monotonic_clock::time_point last_frame_;
376
377 // A queue of camera frames so that we can add a time delay to the data
378 // coming from the cameras.
379 std::queue<std::tuple<aos::monotonic_clock::time_point,
380 std::unique_ptr<ImageMatchResultT>>>
381 camera_delay_queue_;
382
James Kuszmaulaca88782021-04-24 16:48:45 -0700383 // Offset to add to the camera for actually taking the images, to simulate an
384 // inaccurate calibration.
385 Eigen::Matrix<double, 4, 4> camera_calibration_offset_ =
386 Eigen::Matrix<double, 4, 4>::Identity();
387
James Kuszmaul5398fae2020-02-17 16:44:03 -0800388 void set_enable_cameras(bool enable) { enable_cameras_ = enable; }
James Kuszmaul688a2b02020-02-19 18:26:33 -0800389 void set_camera_is_turreted(bool turreted) { is_turreted_ = turreted; }
390
391 void set_turret(double position, double velocity) {
392 turret_position_ = position;
393 turret_velocity_ = velocity;
394 }
395
396 void SendGoal(double left, double right) {
397 auto builder = drivetrain_goal_sender_.MakeBuilder();
398
399 Goal::Builder drivetrain_builder = builder.MakeBuilder<Goal>();
400 drivetrain_builder.add_controller_type(
401 frc971::control_loops::drivetrain::ControllerType::MOTION_PROFILE);
402 drivetrain_builder.add_left_goal(left);
403 drivetrain_builder.add_right_goal(right);
404
milind1f1dca32021-07-03 13:50:07 -0700405 EXPECT_EQ(builder.Send(drivetrain_builder.Finish()),
406 aos::RawSender::Error::kOk);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800407 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800408
409 private:
James Kuszmaul688a2b02020-02-19 18:26:33 -0800410 void UpdateTurretPosition() {
411 turret_position_ +=
412 turret_velocity_ *
413 aos::time::DurationInSeconds(monotonic_now() - last_turret_update_);
414 last_turret_update_ = monotonic_now();
415 }
416
James Kuszmaul5398fae2020-02-17 16:44:03 -0800417 bool enable_cameras_ = false;
James Kuszmaul688a2b02020-02-19 18:26:33 -0800418 // Whether to make the camera be on the turret or not.
419 bool is_turreted_ = true;
420
421 // The time at which we last incremented turret_position_.
422 monotonic_clock::time_point last_turret_update_ = monotonic_clock::min_time;
423 // Current turret position and velocity. These are set directly by the user in
424 // the test, and if velocity is non-zero, then we will automatically increment
425 // turret_position_ with every timestep.
426 double turret_position_ = 0.0; // rad
427 double turret_velocity_ = 0.0; // rad / sec
James Kuszmaul5398fae2020-02-17 16:44:03 -0800428
429 std::unique_ptr<aos::EventLoop> logger_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800430 std::unique_ptr<aos::logger::Logger> logger_;
431};
432
433// Tests that no camera updates, combined with a perfect model, results in no
434// error.
435TEST_F(LocalizedDrivetrainTest, NoCameraUpdate) {
436 SetEnabled(true);
437 set_enable_cameras(false);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800438 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800439
James Kuszmaul688a2b02020-02-19 18:26:33 -0800440 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800441
James Kuszmaul0a981402021-10-09 21:00:34 -0700442 RunFor(chrono::seconds(10));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800443 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700444 EXPECT_TRUE(VerifyEstimatorAccurate(5e-3));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800445}
446
James Kuszmaul7f55f072020-03-01 10:21:26 -0800447// Tests that we can drive in a straight line and have things estimate
448// correctly.
449TEST_F(LocalizedDrivetrainTest, NoCameraUpdateStraightLine) {
450 SetEnabled(true);
451 set_enable_cameras(false);
452 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
453
454 SendGoal(1.0, 1.0);
455
James Kuszmaul0a981402021-10-09 21:00:34 -0700456 RunFor(chrono::seconds(3));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800457 VerifyNearGoal();
458 // Due to accelerometer drift, the straight-line driving tends to be less
459 // accurate...
Austin Schuhcadb3292021-01-23 20:24:17 -0800460 EXPECT_TRUE(VerifyEstimatorAccurate(0.15));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800461}
462
James Kuszmaul688a2b02020-02-19 18:26:33 -0800463// Tests that camera updates with a perfect models results in no errors.
James Kuszmaul5398fae2020-02-17 16:44:03 -0800464TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdate) {
465 SetEnabled(true);
466 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800467 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800468
James Kuszmaul688a2b02020-02-19 18:26:33 -0800469 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800470
James Kuszmaul5398fae2020-02-17 16:44:03 -0800471 RunFor(chrono::seconds(3));
472 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700473 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800474}
475
James Kuszmaulaca88782021-04-24 16:48:45 -0700476// Tests that camera updates with a perfect model but incorrect camera pitch
477// results in no errors.
478TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdateWithBadPitch) {
479 // Introduce some camera pitch.
480 camera_calibration_offset_.template block<3, 3>(0, 0) =
481 Eigen::AngleAxis<double>(0.1, Eigen::Vector3d::UnitY())
482 .toRotationMatrix();
483 SetEnabled(true);
484 set_enable_cameras(true);
485 set_camera_is_turreted(true);
486
487 SendGoal(-1.0, 1.0);
488
489 RunFor(chrono::seconds(3));
490 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700491 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaulaca88782021-04-24 16:48:45 -0700492}
493
James Kuszmaul688a2b02020-02-19 18:26:33 -0800494// Tests that camera updates with a constant initial error in the position
James Kuszmaul5398fae2020-02-17 16:44:03 -0800495// results in convergence.
496TEST_F(LocalizedDrivetrainTest, InitialPositionError) {
497 SetEnabled(true);
498 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800499 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800500 drivetrain_plant_.mutable_state()->topRows(3) +=
501 Eigen::Vector3d(0.1, 0.1, 0.01);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800502
James Kuszmaul688a2b02020-02-19 18:26:33 -0800503 // Confirm that some translational movement does get handled correctly.
504 SendGoal(-0.9, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800505
James Kuszmaul5398fae2020-02-17 16:44:03 -0800506 // Give the filters enough time to converge.
507 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700508 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800509 EXPECT_TRUE(VerifyEstimatorAccurate(4e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800510}
511
512// Tests that camera updates using a non-turreted camera work.
513TEST_F(LocalizedDrivetrainTest, InitialPositionErrorNoTurret) {
514 SetEnabled(true);
515 set_enable_cameras(true);
516 set_camera_is_turreted(false);
517 drivetrain_plant_.mutable_state()->topRows(3) +=
518 Eigen::Vector3d(0.1, 0.1, 0.01);
519
520 SendGoal(-1.0, 1.0);
521
522 // Give the filters enough time to converge.
523 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700524 VerifyNearGoal(5e-2);
Austin Schuheb718632021-10-22 22:32:57 -0700525 EXPECT_TRUE(VerifyEstimatorAccurate(0.1));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800526}
527
528// Tests that we are able to handle a constant, non-zero turret angle.
529TEST_F(LocalizedDrivetrainTest, NonZeroTurret) {
530 SetEnabled(true);
531 set_enable_cameras(true);
532 set_camera_is_turreted(true);
533 set_turret(1.0, 0.0);
534 drivetrain_plant_.mutable_state()->topRows(3) +=
535 Eigen::Vector3d(0.1, 0.1, 0.0);
536
537 SendGoal(-1.0, 1.0);
538
539 // Give the filters enough time to converge.
540 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700541 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800542 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800543}
544
545// Tests that we are able to handle a constant velocity turret.
546TEST_F(LocalizedDrivetrainTest, MovingTurret) {
547 SetEnabled(true);
548 set_enable_cameras(true);
549 set_camera_is_turreted(true);
550 set_turret(0.0, 0.2);
551 drivetrain_plant_.mutable_state()->topRows(3) +=
552 Eigen::Vector3d(0.1, 0.1, 0.0);
553
554 SendGoal(-1.0, 1.0);
555
556 // Give the filters enough time to converge.
557 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700558 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800559 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800560}
561
562// Tests that we reject camera measurements when the turret is spinning too
563// fast.
564TEST_F(LocalizedDrivetrainTest, TooFastTurret) {
565 SetEnabled(true);
566 set_enable_cameras(true);
567 set_camera_is_turreted(true);
568 set_turret(0.0, -10.0);
569 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
570 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
571
572 SendGoal(-1.0, 1.0);
573
574 RunFor(chrono::seconds(10));
575 EXPECT_FALSE(VerifyEstimatorAccurate(1e-3));
576 // If we remove the disturbance, we should now be correct.
577 drivetrain_plant_.mutable_state()->topRows(3) -= disturbance;
James Kuszmaul0a981402021-10-09 21:00:34 -0700578 VerifyNearGoal(5e-2);
579 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800580}
581
582// Tests that we don't reject camera measurements when the turret is spinning
583// too fast but we aren't using a camera attached to the turret.
584TEST_F(LocalizedDrivetrainTest, TooFastTurretDoesntAffectFixedCamera) {
585 SetEnabled(true);
586 set_enable_cameras(true);
587 set_camera_is_turreted(false);
588 set_turret(0.0, -10.0);
589 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
590 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
591
592 SendGoal(-1.0, 1.0);
593
594 RunFor(chrono::seconds(10));
595 VerifyNearGoal(5e-3);
Austin Schuheb718632021-10-22 22:32:57 -0700596 EXPECT_TRUE(VerifyEstimatorAccurate(5e-2));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800597}
598
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700599// Tests that we don't blow up if we stop getting updates for an extended period
600// of time and fall behind on fetching fron the cameras.
601TEST_F(LocalizedDrivetrainTest, FetchersHandleTimeGap) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700602 set_enable_cameras(false);
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700603 set_send_delay(std::chrono::seconds(0));
604 event_loop_factory()->set_network_delay(std::chrono::nanoseconds(1));
605 test_event_loop_
606 ->AddTimer([this]() { drivetrain_plant_.set_send_messages(false); })
607 ->Setup(test_event_loop_->monotonic_now());
608 test_event_loop_->AddPhasedLoop(
609 [this](int) {
610 auto builder = camera_sender_.MakeBuilder();
611 ImageMatchResultT image;
milind1f1dca32021-07-03 13:50:07 -0700612 ASSERT_EQ(builder.Send(ImageMatchResult::Pack(*builder.fbb(), &image)),
613 aos::RawSender::Error::kOk);
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700614 },
milind945708b2021-07-03 13:30:15 -0700615 std::chrono::milliseconds(40));
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700616 test_event_loop_
617 ->AddTimer([this]() {
618 drivetrain_plant_.set_send_messages(true);
619 SimulateSensorReset();
620 })
621 ->Setup(test_event_loop_->monotonic_now() + std::chrono::seconds(10));
622
623 RunFor(chrono::seconds(20));
624}
625
James Kuszmaul5398fae2020-02-17 16:44:03 -0800626} // namespace testing
627} // namespace drivetrain
628} // namespace control_loops
629} // namespace y2020