blob: 90076c02065fdae4cfe7955da643dacb96192cff [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
Philipp Schrader790cb542023-07-05 21:06:52 -07005#include "gtest/gtest.h"
6
Austin Schuhb06f03b2021-02-17 22:00:37 -08007#include "aos/events/logging/log_writer.h"
James Kuszmaul958b21e2020-02-26 21:51:40 -08008#include "aos/network/message_bridge_server_generated.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -08009#include "aos/network/team_number.h"
James Kuszmaul61750662021-06-21 21:32:33 -070010#include "frc971/control_loops/control_loop_test.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -080011#include "frc971/control_loops/drivetrain/drivetrain.h"
12#include "frc971/control_loops/drivetrain/drivetrain_test_lib.h"
13#include "frc971/control_loops/team_number_test_environment.h"
14#include "y2020/control_loops/drivetrain/drivetrain_base.h"
James Kuszmaul688a2b02020-02-19 18:26:33 -080015#include "y2020/control_loops/superstructure/superstructure_status_generated.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -080016
17DEFINE_string(output_file, "",
18 "If set, logs all channels to the provided logfile.");
19
20// This file tests that the full 2020 localizer behaves sanely.
21
Stephan Pleinesf63bde82024-01-13 15:59:33 -080022namespace y2020::control_loops::drivetrain::testing {
James Kuszmaul5398fae2020-02-17 16:44:03 -080023
Austin Schuh66168842021-08-17 19:42:21 -070024using aos::logger::BootTimestamp;
James Kuszmaul5398fae2020-02-17 16:44:03 -080025using frc971::control_loops::drivetrain::DrivetrainConfig;
26using frc971::control_loops::drivetrain::Goal;
27using frc971::control_loops::drivetrain::LocalizerControl;
Brian Silverman1f345222020-09-24 21:14:48 -070028using frc971::vision::sift::CameraCalibrationT;
29using frc971::vision::sift::CameraPoseT;
James Kuszmaul5398fae2020-02-17 16:44:03 -080030using frc971::vision::sift::ImageMatchResult;
31using frc971::vision::sift::ImageMatchResultT;
James Kuszmaul5398fae2020-02-17 16:44:03 -080032using frc971::vision::sift::TransformationMatrixT;
33
34namespace {
35DrivetrainConfig<double> GetTest2020DrivetrainConfig() {
36 DrivetrainConfig<double> config = GetDrivetrainConfig();
37 return config;
38}
39
40// Copies an Eigen matrix into a row-major vector of the data.
41std::vector<float> MatrixToVector(const Eigen::Matrix<double, 4, 4> &H) {
42 std::vector<float> data;
43 for (int row = 0; row < 4; ++row) {
44 for (int col = 0; col < 4; ++col) {
45 data.push_back(H(row, col));
46 }
47 }
48 return data;
49}
50
51// Provides the location of the turret to use for simulation. Mostly we care
52// about providing a location that is not perfectly aligned with the robot's
53// origin.
54Eigen::Matrix<double, 4, 4> TurretRobotTransformation() {
55 Eigen::Matrix<double, 4, 4> H;
56 H.setIdentity();
James Kuszmaul688a2b02020-02-19 18:26:33 -080057 H.block<3, 1>(0, 3) << 1, 1.1, 0.9;
James Kuszmaul5398fae2020-02-17 16:44:03 -080058 return H;
59}
60
61// Provides the location of the camera on the turret.
62// TODO(james): Also simulate a fixed camera that is *not* on the turret.
63Eigen::Matrix<double, 4, 4> CameraTurretTransformation() {
64 Eigen::Matrix<double, 4, 4> H;
65 H.setIdentity();
66 H.block<3, 1>(0, 3) << 0.1, 0, 0;
67 // Introduce a bit of pitch to make sure that we're exercising all the code.
68 H.block<3, 3>(0, 0) =
James Kuszmaul688a2b02020-02-19 18:26:33 -080069 Eigen::AngleAxis<double>(0.1, Eigen::Vector3d::UnitY()) *
James Kuszmaul5398fae2020-02-17 16:44:03 -080070 H.block<3, 3>(0, 0);
71 return H;
72}
73
74// The absolute target location to use. Not meant to correspond with a
75// particular field target.
76// TODO(james): Make more targets.
James Kuszmaul688a2b02020-02-19 18:26:33 -080077std::vector<Eigen::Matrix<double, 4, 4>> TargetLocations() {
78 std::vector<Eigen::Matrix<double, 4, 4>> locations;
James Kuszmaul5398fae2020-02-17 16:44:03 -080079 Eigen::Matrix<double, 4, 4> H;
80 H.setIdentity();
81 H.block<3, 1>(0, 3) << 10.0, 0, 0;
James Kuszmaul688a2b02020-02-19 18:26:33 -080082 locations.push_back(H);
83 H.block<3, 1>(0, 3) << -10.0, 0, 0;
James Kuszmaul5a46c8d2021-09-03 19:33:48 -070084 H.block<3, 3>(0, 0) =
85 Eigen::AngleAxis<double>(1.1, Eigen::Vector3d::UnitZ()) *
86 H.block<3, 3>(0, 0);
James Kuszmaul688a2b02020-02-19 18:26:33 -080087 locations.push_back(H);
88 return locations;
James Kuszmaul5398fae2020-02-17 16:44:03 -080089}
James Kuszmaul958b21e2020-02-26 21:51:40 -080090
James Kuszmaul8866e642022-06-10 16:00:36 -070091constexpr std::chrono::seconds kPiTimeOffset(10);
James Kuszmaul5398fae2020-02-17 16:44:03 -080092} // namespace
93
94namespace chrono = std::chrono;
James Kuszmaul5398fae2020-02-17 16:44:03 -080095using aos::monotonic_clock;
Brian Silverman1f345222020-09-24 21:14:48 -070096using frc971::control_loops::drivetrain::DrivetrainLoop;
97using frc971::control_loops::drivetrain::testing::DrivetrainSimulation;
James Kuszmaul5398fae2020-02-17 16:44:03 -080098
James Kuszmaul61750662021-06-21 21:32:33 -070099class LocalizedDrivetrainTest : public frc971::testing::ControlLoopTest {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800100 protected:
101 // We must use the 2020 drivetrain config so that we don't have to deal
102 // with shifting:
103 LocalizedDrivetrainTest()
James Kuszmaul61750662021-06-21 21:32:33 -0700104 : frc971::testing::ControlLoopTest(
James Kuszmaul5398fae2020-02-17 16:44:03 -0800105 aos::configuration::ReadConfig(
106 "y2020/control_loops/drivetrain/simulation_config.json"),
Austin Schuh0debde12022-08-17 16:25:17 -0700107 GetTest2020DrivetrainConfig().dt,
108 {{BootTimestamp::epoch() + kPiTimeOffset,
109 BootTimestamp::epoch() + kPiTimeOffset,
110 BootTimestamp::epoch() + kPiTimeOffset,
111 BootTimestamp::epoch() + kPiTimeOffset,
112 BootTimestamp::epoch() + kPiTimeOffset,
113 BootTimestamp::epoch() + kPiTimeOffset, BootTimestamp::epoch()}}),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800114 roborio_(aos::configuration::GetNode(configuration(), "roborio")),
115 pi1_(aos::configuration::GetNode(configuration(), "pi1")),
116 test_event_loop_(MakeEventLoop("test", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800117 drivetrain_goal_sender_(
118 test_event_loop_->MakeSender<Goal>("/drivetrain")),
119 drivetrain_goal_fetcher_(
120 test_event_loop_->MakeFetcher<Goal>("/drivetrain")),
James Kuszmaul0a981402021-10-09 21:00:34 -0700121 drivetrain_status_fetcher_(
122 test_event_loop_
123 ->MakeFetcher<frc971::control_loops::drivetrain::Status>(
124 "/drivetrain")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800125 localizer_control_sender_(
126 test_event_loop_->MakeSender<LocalizerControl>("/drivetrain")),
James Kuszmaul688a2b02020-02-19 18:26:33 -0800127 superstructure_status_sender_(
128 test_event_loop_->MakeSender<superstructure::Status>(
129 "/superstructure")),
James Kuszmaul958b21e2020-02-26 21:51:40 -0800130 server_statistics_sender_(
131 test_event_loop_->MakeSender<aos::message_bridge::ServerStatistics>(
132 "/aos")),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800133 drivetrain_event_loop_(MakeEventLoop("drivetrain", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800134 dt_config_(GetTest2020DrivetrainConfig()),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800135 pi1_event_loop_(MakeEventLoop("test", pi1_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800136 camera_sender_(
Austin Schuh6aa77be2020-02-22 21:06:40 -0800137 pi1_event_loop_->MakeSender<ImageMatchResult>("/pi1/camera")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800138 localizer_(drivetrain_event_loop_.get(), dt_config_),
139 drivetrain_(dt_config_, drivetrain_event_loop_.get(), &localizer_),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800140 drivetrain_plant_event_loop_(MakeEventLoop("plant", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800141 drivetrain_plant_(drivetrain_plant_event_loop_.get(), dt_config_),
142 last_frame_(monotonic_now()) {
James Kuszmaul9c128122021-03-22 22:24:36 -0700143 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), roborio_), 6);
Austin Schuh87dd3832021-01-01 23:07:31 -0800144 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), pi1_), 1);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800145 set_team_id(frc971::control_loops::testing::kTeamNumber);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800146 set_battery_voltage(12.0);
147
148 if (!FLAGS_output_file.empty()) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800149 logger_event_loop_ = MakeEventLoop("logger", roborio_);
Brian Silverman1f345222020-09-24 21:14:48 -0700150 logger_ = std::make_unique<aos::logger::Logger>(logger_event_loop_.get());
James Kuszmaul0a981402021-10-09 21:00:34 -0700151 logger_->StartLoggingOnRun(FLAGS_output_file);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800152 }
153
154 test_event_loop_->MakeWatcher(
155 "/drivetrain",
156 [this](const frc971::control_loops::drivetrain::Status &) {
157 // Needs to do camera updates right after we run the control loop.
158 if (enable_cameras_) {
159 SendDelayedFrames();
160 if (last_frame_ + std::chrono::milliseconds(100) <
161 monotonic_now()) {
162 CaptureFrames();
163 last_frame_ = monotonic_now();
164 }
165 }
Brian Silverman1f345222020-09-24 21:14:48 -0700166 });
James Kuszmaul688a2b02020-02-19 18:26:33 -0800167
168 test_event_loop_->AddPhasedLoop(
169 [this](int) {
James Kuszmaul0a981402021-10-09 21:00:34 -0700170 // TODO(james): This is wrong. At a bare minimum, it is missing a boot
171 // UUID, and this is probably the wrong pattern entirely.
James Kuszmaul958b21e2020-02-26 21:51:40 -0800172 auto builder = server_statistics_sender_.MakeBuilder();
173 auto name_offset = builder.fbb()->CreateString("pi1");
174 auto node_builder = builder.MakeBuilder<aos::Node>();
175 node_builder.add_name(name_offset);
176 auto node_offset = node_builder.Finish();
177 auto connection_builder =
178 builder.MakeBuilder<aos::message_bridge::ServerConnection>();
179 connection_builder.add_node(node_offset);
180 connection_builder.add_monotonic_offset(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700181 chrono::duration_cast<chrono::nanoseconds>(kPiTimeOffset)
James Kuszmaul958b21e2020-02-26 21:51:40 -0800182 .count());
183 auto connection_offset = connection_builder.Finish();
184 auto connections_offset =
185 builder.fbb()->CreateVector(&connection_offset, 1);
186 auto statistics_builder =
187 builder.MakeBuilder<aos::message_bridge::ServerStatistics>();
188 statistics_builder.add_connections(connections_offset);
milind1f1dca32021-07-03 13:50:07 -0700189 CHECK_EQ(builder.Send(statistics_builder.Finish()),
190 aos::RawSender::Error::kOk);
James Kuszmaul958b21e2020-02-26 21:51:40 -0800191 },
192 chrono::milliseconds(500));
193
194 test_event_loop_->AddPhasedLoop(
195 [this](int) {
James Kuszmaul688a2b02020-02-19 18:26:33 -0800196 // Also use the opportunity to send out turret messages.
197 UpdateTurretPosition();
198 auto builder = superstructure_status_sender_.MakeBuilder();
199 auto turret_builder =
200 builder
201 .MakeBuilder<frc971::control_loops::
202 PotAndAbsoluteEncoderProfiledJointStatus>();
203 turret_builder.add_position(turret_position_);
204 turret_builder.add_velocity(turret_velocity_);
205 auto turret_offset = turret_builder.Finish();
206 auto status_builder = builder.MakeBuilder<superstructure::Status>();
207 status_builder.add_turret(turret_offset);
milind1f1dca32021-07-03 13:50:07 -0700208 CHECK_EQ(builder.Send(status_builder.Finish()),
209 aos::RawSender::Error::kOk);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800210 },
Yash Chainania6fe97b2021-12-15 21:01:11 -0800211 frc971::controls::kLoopFrequency);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800212
James Kuszmaul286b4282020-02-26 20:29:32 -0800213 test_event_loop_->OnRun([this]() { SetStartingPosition({3.0, 2.0, 0.0}); });
214
James Kuszmaul5398fae2020-02-17 16:44:03 -0800215 // Run for enough time to allow the gyro/imu zeroing code to run.
James Kuszmaul0a981402021-10-09 21:00:34 -0700216 RunFor(std::chrono::seconds(15));
217 CHECK(drivetrain_status_fetcher_.Fetch());
218 EXPECT_TRUE(CHECK_NOTNULL(drivetrain_status_fetcher_->zeroing())->zeroed());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800219 }
220
221 virtual ~LocalizedDrivetrainTest() override {}
222
223 void SetStartingPosition(const Eigen::Matrix<double, 3, 1> &xytheta) {
224 *drivetrain_plant_.mutable_state() << xytheta.x(), xytheta.y(),
225 xytheta(2, 0), 0.0, 0.0;
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700226 Eigen::Matrix<double, Localizer::HybridEkf::kNStates, 1> localizer_state;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800227 localizer_state.setZero();
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700228 localizer_state.block<3, 1>(0, 0) = xytheta;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800229 localizer_.Reset(monotonic_now(), localizer_state);
230 }
231
James Kuszmaul0a981402021-10-09 21:00:34 -0700232 void VerifyNearGoal(double eps = 1e-2) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800233 drivetrain_goal_fetcher_.Fetch();
234 EXPECT_NEAR(drivetrain_goal_fetcher_->left_goal(),
235 drivetrain_plant_.GetLeftPosition(), eps);
236 EXPECT_NEAR(drivetrain_goal_fetcher_->right_goal(),
237 drivetrain_plant_.GetRightPosition(), eps);
238 }
239
James Kuszmaul688a2b02020-02-19 18:26:33 -0800240 ::testing::AssertionResult IsNear(double expected, double actual,
241 double epsilon) {
242 if (std::abs(expected - actual) < epsilon) {
243 return ::testing::AssertionSuccess();
244 } else {
245 return ::testing::AssertionFailure()
246 << "Expected " << expected << " but got " << actual
247 << " with a max difference of " << epsilon
248 << " and an actual difference of " << std::abs(expected - actual);
249 }
250 }
251 ::testing::AssertionResult VerifyEstimatorAccurate(double eps) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800252 const Eigen::Matrix<double, 5, 1> true_state = drivetrain_plant_.state();
James Kuszmaul688a2b02020-02-19 18:26:33 -0800253 ::testing::AssertionResult result(true);
254 if (!(result = IsNear(localizer_.x(), true_state(0), eps))) {
255 return result;
256 }
257 if (!(result = IsNear(localizer_.y(), true_state(1), eps))) {
258 return result;
259 }
260 if (!(result = IsNear(localizer_.theta(), true_state(2), eps))) {
261 return result;
262 }
263 if (!(result = IsNear(localizer_.left_velocity(), true_state(3), eps))) {
264 return result;
265 }
266 if (!(result = IsNear(localizer_.right_velocity(), true_state(4), eps))) {
267 return result;
268 }
269 return result;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800270 }
271
272 // Goes through and captures frames on the camera(s), queueing them up to be
273 // sent by SendDelayedFrames().
274 void CaptureFrames() {
275 const frc971::control_loops::Pose robot_pose(
276 {drivetrain_plant_.GetPosition().x(),
277 drivetrain_plant_.GetPosition().y(), 0.0},
278 drivetrain_plant_.state()(2, 0));
279 std::unique_ptr<ImageMatchResultT> frame(new ImageMatchResultT());
280
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800281 for (const auto &H_field_target : TargetLocations()) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800282 std::unique_ptr<CameraPoseT> camera_target(new CameraPoseT());
283
284 camera_target->field_to_target.reset(new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800285 camera_target->field_to_target->data = MatrixToVector(H_field_target);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800286
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800287 Eigen::Matrix<double, 4, 4> H_turret_camera =
James Kuszmaul688a2b02020-02-19 18:26:33 -0800288 Eigen::Matrix<double, 4, 4>::Identity();
289 if (is_turreted_) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800290 H_turret_camera = frc971::control_loops::TransformationMatrixForYaw(
James Kuszmaul688a2b02020-02-19 18:26:33 -0800291 turret_position_) *
292 CameraTurretTransformation();
293 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800294
295 // TODO(james): Use non-zero turret angles.
296 camera_target->camera_to_target.reset(new TransformationMatrixT());
James Kuszmaulaca88782021-04-24 16:48:45 -0700297 camera_target->camera_to_target->data = MatrixToVector(
298 (robot_pose.AsTransformationMatrix() * TurretRobotTransformation() *
299 H_turret_camera * camera_calibration_offset_)
300 .inverse() *
301 H_field_target);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800302
303 frame->camera_poses.emplace_back(std::move(camera_target));
304 }
305
306 frame->image_monotonic_timestamp_ns =
307 chrono::duration_cast<chrono::nanoseconds>(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800308 event_loop_factory()
309 ->GetNodeEventLoopFactory(pi1_)
310 ->monotonic_now()
311 .time_since_epoch())
James Kuszmaul5398fae2020-02-17 16:44:03 -0800312 .count();
313 frame->camera_calibration.reset(new CameraCalibrationT());
314 {
315 frame->camera_calibration->fixed_extrinsics.reset(
316 new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800317 TransformationMatrixT *H_robot_turret =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800318 frame->camera_calibration->fixed_extrinsics.get();
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800319 H_robot_turret->data = MatrixToVector(TurretRobotTransformation());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800320 }
James Kuszmaul688a2b02020-02-19 18:26:33 -0800321
322 if (is_turreted_) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800323 frame->camera_calibration->turret_extrinsics.reset(
324 new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800325 TransformationMatrixT *H_turret_camera =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800326 frame->camera_calibration->turret_extrinsics.get();
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800327 H_turret_camera->data = MatrixToVector(CameraTurretTransformation());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800328 }
329
330 camera_delay_queue_.emplace(monotonic_now(), std::move(frame));
331 }
332
333 // Actually sends out all the camera frames.
334 void SendDelayedFrames() {
335 const std::chrono::milliseconds camera_latency(150);
336 while (!camera_delay_queue_.empty() &&
337 std::get<0>(camera_delay_queue_.front()) <
338 monotonic_now() - camera_latency) {
339 auto builder = camera_sender_.MakeBuilder();
milind1f1dca32021-07-03 13:50:07 -0700340 ASSERT_EQ(
341 builder.Send(ImageMatchResult::Pack(
342 *builder.fbb(), std::get<1>(camera_delay_queue_.front()).get())),
343 aos::RawSender::Error::kOk);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800344 camera_delay_queue_.pop();
345 }
346 }
347
Austin Schuh6aa77be2020-02-22 21:06:40 -0800348 const aos::Node *const roborio_;
349 const aos::Node *const pi1_;
350
James Kuszmaul5398fae2020-02-17 16:44:03 -0800351 std::unique_ptr<aos::EventLoop> test_event_loop_;
352 aos::Sender<Goal> drivetrain_goal_sender_;
353 aos::Fetcher<Goal> drivetrain_goal_fetcher_;
James Kuszmaul0a981402021-10-09 21:00:34 -0700354 aos::Fetcher<frc971::control_loops::drivetrain::Status>
355 drivetrain_status_fetcher_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800356 aos::Sender<LocalizerControl> localizer_control_sender_;
James Kuszmaul688a2b02020-02-19 18:26:33 -0800357 aos::Sender<superstructure::Status> superstructure_status_sender_;
James Kuszmaul958b21e2020-02-26 21:51:40 -0800358 aos::Sender<aos::message_bridge::ServerStatistics> server_statistics_sender_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800359
360 std::unique_ptr<aos::EventLoop> drivetrain_event_loop_;
Brian Silverman1f345222020-09-24 21:14:48 -0700361 const frc971::control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800362
Austin Schuh6aa77be2020-02-22 21:06:40 -0800363 std::unique_ptr<aos::EventLoop> pi1_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800364 aos::Sender<ImageMatchResult> camera_sender_;
365
366 Localizer localizer_;
367 DrivetrainLoop drivetrain_;
368
369 std::unique_ptr<aos::EventLoop> drivetrain_plant_event_loop_;
370 DrivetrainSimulation drivetrain_plant_;
371 monotonic_clock::time_point last_frame_;
372
373 // A queue of camera frames so that we can add a time delay to the data
374 // coming from the cameras.
375 std::queue<std::tuple<aos::monotonic_clock::time_point,
376 std::unique_ptr<ImageMatchResultT>>>
377 camera_delay_queue_;
378
James Kuszmaulaca88782021-04-24 16:48:45 -0700379 // Offset to add to the camera for actually taking the images, to simulate an
380 // inaccurate calibration.
381 Eigen::Matrix<double, 4, 4> camera_calibration_offset_ =
382 Eigen::Matrix<double, 4, 4>::Identity();
383
James Kuszmaul5398fae2020-02-17 16:44:03 -0800384 void set_enable_cameras(bool enable) { enable_cameras_ = enable; }
James Kuszmaul688a2b02020-02-19 18:26:33 -0800385 void set_camera_is_turreted(bool turreted) { is_turreted_ = turreted; }
386
387 void set_turret(double position, double velocity) {
388 turret_position_ = position;
389 turret_velocity_ = velocity;
390 }
391
392 void SendGoal(double left, double right) {
393 auto builder = drivetrain_goal_sender_.MakeBuilder();
394
395 Goal::Builder drivetrain_builder = builder.MakeBuilder<Goal>();
396 drivetrain_builder.add_controller_type(
397 frc971::control_loops::drivetrain::ControllerType::MOTION_PROFILE);
398 drivetrain_builder.add_left_goal(left);
399 drivetrain_builder.add_right_goal(right);
400
milind1f1dca32021-07-03 13:50:07 -0700401 EXPECT_EQ(builder.Send(drivetrain_builder.Finish()),
402 aos::RawSender::Error::kOk);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800403 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800404
405 private:
James Kuszmaul688a2b02020-02-19 18:26:33 -0800406 void UpdateTurretPosition() {
407 turret_position_ +=
408 turret_velocity_ *
409 aos::time::DurationInSeconds(monotonic_now() - last_turret_update_);
410 last_turret_update_ = monotonic_now();
411 }
412
James Kuszmaul5398fae2020-02-17 16:44:03 -0800413 bool enable_cameras_ = false;
James Kuszmaul688a2b02020-02-19 18:26:33 -0800414 // Whether to make the camera be on the turret or not.
415 bool is_turreted_ = true;
416
417 // The time at which we last incremented turret_position_.
418 monotonic_clock::time_point last_turret_update_ = monotonic_clock::min_time;
419 // Current turret position and velocity. These are set directly by the user in
420 // the test, and if velocity is non-zero, then we will automatically increment
421 // turret_position_ with every timestep.
422 double turret_position_ = 0.0; // rad
423 double turret_velocity_ = 0.0; // rad / sec
James Kuszmaul5398fae2020-02-17 16:44:03 -0800424
425 std::unique_ptr<aos::EventLoop> logger_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800426 std::unique_ptr<aos::logger::Logger> logger_;
427};
428
429// Tests that no camera updates, combined with a perfect model, results in no
430// error.
431TEST_F(LocalizedDrivetrainTest, NoCameraUpdate) {
432 SetEnabled(true);
433 set_enable_cameras(false);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800434 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800435
James Kuszmaul688a2b02020-02-19 18:26:33 -0800436 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800437
James Kuszmaul0a981402021-10-09 21:00:34 -0700438 RunFor(chrono::seconds(10));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800439 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700440 EXPECT_TRUE(VerifyEstimatorAccurate(5e-3));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800441}
442
James Kuszmaul7f55f072020-03-01 10:21:26 -0800443// Tests that we can drive in a straight line and have things estimate
444// correctly.
445TEST_F(LocalizedDrivetrainTest, NoCameraUpdateStraightLine) {
446 SetEnabled(true);
447 set_enable_cameras(false);
448 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
449
450 SendGoal(1.0, 1.0);
451
James Kuszmaul0a981402021-10-09 21:00:34 -0700452 RunFor(chrono::seconds(3));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800453 VerifyNearGoal();
454 // Due to accelerometer drift, the straight-line driving tends to be less
455 // accurate...
Austin Schuhcadb3292021-01-23 20:24:17 -0800456 EXPECT_TRUE(VerifyEstimatorAccurate(0.15));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800457}
458
James Kuszmaul688a2b02020-02-19 18:26:33 -0800459// Tests that camera updates with a perfect models results in no errors.
James Kuszmaul5398fae2020-02-17 16:44:03 -0800460TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdate) {
461 SetEnabled(true);
462 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800463 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800464
James Kuszmaul688a2b02020-02-19 18:26:33 -0800465 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800466
James Kuszmaul5398fae2020-02-17 16:44:03 -0800467 RunFor(chrono::seconds(3));
468 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700469 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800470}
471
James Kuszmaulaca88782021-04-24 16:48:45 -0700472// Tests that camera updates with a perfect model but incorrect camera pitch
473// results in no errors.
474TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdateWithBadPitch) {
475 // Introduce some camera pitch.
476 camera_calibration_offset_.template block<3, 3>(0, 0) =
477 Eigen::AngleAxis<double>(0.1, Eigen::Vector3d::UnitY())
478 .toRotationMatrix();
479 SetEnabled(true);
480 set_enable_cameras(true);
481 set_camera_is_turreted(true);
482
483 SendGoal(-1.0, 1.0);
484
485 RunFor(chrono::seconds(3));
486 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700487 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaulaca88782021-04-24 16:48:45 -0700488}
489
James Kuszmaul688a2b02020-02-19 18:26:33 -0800490// Tests that camera updates with a constant initial error in the position
James Kuszmaul5398fae2020-02-17 16:44:03 -0800491// results in convergence.
492TEST_F(LocalizedDrivetrainTest, InitialPositionError) {
493 SetEnabled(true);
494 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800495 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800496 drivetrain_plant_.mutable_state()->topRows(3) +=
497 Eigen::Vector3d(0.1, 0.1, 0.01);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800498
James Kuszmaul688a2b02020-02-19 18:26:33 -0800499 // Confirm that some translational movement does get handled correctly.
500 SendGoal(-0.9, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800501
James Kuszmaul5398fae2020-02-17 16:44:03 -0800502 // Give the filters enough time to converge.
503 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700504 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800505 EXPECT_TRUE(VerifyEstimatorAccurate(4e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800506}
507
508// Tests that camera updates using a non-turreted camera work.
509TEST_F(LocalizedDrivetrainTest, InitialPositionErrorNoTurret) {
510 SetEnabled(true);
511 set_enable_cameras(true);
512 set_camera_is_turreted(false);
513 drivetrain_plant_.mutable_state()->topRows(3) +=
514 Eigen::Vector3d(0.1, 0.1, 0.01);
515
516 SendGoal(-1.0, 1.0);
517
518 // Give the filters enough time to converge.
519 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700520 VerifyNearGoal(5e-2);
Austin Schuheb718632021-10-22 22:32:57 -0700521 EXPECT_TRUE(VerifyEstimatorAccurate(0.1));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800522}
523
524// Tests that we are able to handle a constant, non-zero turret angle.
525TEST_F(LocalizedDrivetrainTest, NonZeroTurret) {
526 SetEnabled(true);
527 set_enable_cameras(true);
528 set_camera_is_turreted(true);
529 set_turret(1.0, 0.0);
530 drivetrain_plant_.mutable_state()->topRows(3) +=
531 Eigen::Vector3d(0.1, 0.1, 0.0);
532
533 SendGoal(-1.0, 1.0);
534
535 // Give the filters enough time to converge.
536 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700537 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800538 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800539}
540
541// Tests that we are able to handle a constant velocity turret.
542TEST_F(LocalizedDrivetrainTest, MovingTurret) {
543 SetEnabled(true);
544 set_enable_cameras(true);
545 set_camera_is_turreted(true);
546 set_turret(0.0, 0.2);
547 drivetrain_plant_.mutable_state()->topRows(3) +=
548 Eigen::Vector3d(0.1, 0.1, 0.0);
549
550 SendGoal(-1.0, 1.0);
551
552 // Give the filters enough time to converge.
553 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700554 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800555 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800556}
557
558// Tests that we reject camera measurements when the turret is spinning too
559// fast.
560TEST_F(LocalizedDrivetrainTest, TooFastTurret) {
561 SetEnabled(true);
562 set_enable_cameras(true);
563 set_camera_is_turreted(true);
564 set_turret(0.0, -10.0);
565 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
566 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
567
568 SendGoal(-1.0, 1.0);
569
570 RunFor(chrono::seconds(10));
571 EXPECT_FALSE(VerifyEstimatorAccurate(1e-3));
572 // If we remove the disturbance, we should now be correct.
573 drivetrain_plant_.mutable_state()->topRows(3) -= disturbance;
James Kuszmaul0a981402021-10-09 21:00:34 -0700574 VerifyNearGoal(5e-2);
575 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800576}
577
578// Tests that we don't reject camera measurements when the turret is spinning
579// too fast but we aren't using a camera attached to the turret.
580TEST_F(LocalizedDrivetrainTest, TooFastTurretDoesntAffectFixedCamera) {
581 SetEnabled(true);
582 set_enable_cameras(true);
583 set_camera_is_turreted(false);
584 set_turret(0.0, -10.0);
585 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
586 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
587
588 SendGoal(-1.0, 1.0);
589
590 RunFor(chrono::seconds(10));
591 VerifyNearGoal(5e-3);
Austin Schuheb718632021-10-22 22:32:57 -0700592 EXPECT_TRUE(VerifyEstimatorAccurate(5e-2));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800593}
594
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700595// Tests that we don't blow up if we stop getting updates for an extended period
596// of time and fall behind on fetching fron the cameras.
597TEST_F(LocalizedDrivetrainTest, FetchersHandleTimeGap) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700598 set_enable_cameras(false);
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700599 set_send_delay(std::chrono::seconds(0));
600 event_loop_factory()->set_network_delay(std::chrono::nanoseconds(1));
601 test_event_loop_
602 ->AddTimer([this]() { drivetrain_plant_.set_send_messages(false); })
Philipp Schradera6712522023-07-05 20:25:11 -0700603 ->Schedule(test_event_loop_->monotonic_now());
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700604 test_event_loop_->AddPhasedLoop(
605 [this](int) {
606 auto builder = camera_sender_.MakeBuilder();
607 ImageMatchResultT image;
milind1f1dca32021-07-03 13:50:07 -0700608 ASSERT_EQ(builder.Send(ImageMatchResult::Pack(*builder.fbb(), &image)),
609 aos::RawSender::Error::kOk);
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700610 },
milind945708b2021-07-03 13:30:15 -0700611 std::chrono::milliseconds(40));
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700612 test_event_loop_
613 ->AddTimer([this]() {
614 drivetrain_plant_.set_send_messages(true);
615 SimulateSensorReset();
616 })
Philipp Schradera6712522023-07-05 20:25:11 -0700617 ->Schedule(test_event_loop_->monotonic_now() + std::chrono::seconds(10));
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700618
619 RunFor(chrono::seconds(20));
620}
621
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800622} // namespace y2020::control_loops::drivetrain::testing