blob: 9e9e7ddf464c0af0466eccf1a181ad6772df8b16 [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.");
18
19// This file tests that the full 2020 localizer behaves sanely.
20
21namespace y2020 {
22namespace control_loops {
23namespace drivetrain {
24namespace testing {
25
Austin Schuh66168842021-08-17 19:42:21 -070026using aos::logger::BootTimestamp;
James Kuszmaul5398fae2020-02-17 16:44:03 -080027using frc971::control_loops::drivetrain::DrivetrainConfig;
28using frc971::control_loops::drivetrain::Goal;
29using frc971::control_loops::drivetrain::LocalizerControl;
Brian Silverman1f345222020-09-24 21:14:48 -070030using frc971::vision::sift::CameraCalibrationT;
31using frc971::vision::sift::CameraPoseT;
James Kuszmaul5398fae2020-02-17 16:44:03 -080032using frc971::vision::sift::ImageMatchResult;
33using frc971::vision::sift::ImageMatchResultT;
James Kuszmaul5398fae2020-02-17 16:44:03 -080034using frc971::vision::sift::TransformationMatrixT;
35
36namespace {
37DrivetrainConfig<double> GetTest2020DrivetrainConfig() {
38 DrivetrainConfig<double> config = GetDrivetrainConfig();
39 return config;
40}
41
42// Copies an Eigen matrix into a row-major vector of the data.
43std::vector<float> MatrixToVector(const Eigen::Matrix<double, 4, 4> &H) {
44 std::vector<float> data;
45 for (int row = 0; row < 4; ++row) {
46 for (int col = 0; col < 4; ++col) {
47 data.push_back(H(row, col));
48 }
49 }
50 return data;
51}
52
53// Provides the location of the turret to use for simulation. Mostly we care
54// about providing a location that is not perfectly aligned with the robot's
55// origin.
56Eigen::Matrix<double, 4, 4> TurretRobotTransformation() {
57 Eigen::Matrix<double, 4, 4> H;
58 H.setIdentity();
James Kuszmaul688a2b02020-02-19 18:26:33 -080059 H.block<3, 1>(0, 3) << 1, 1.1, 0.9;
James Kuszmaul5398fae2020-02-17 16:44:03 -080060 return H;
61}
62
63// Provides the location of the camera on the turret.
64// TODO(james): Also simulate a fixed camera that is *not* on the turret.
65Eigen::Matrix<double, 4, 4> CameraTurretTransformation() {
66 Eigen::Matrix<double, 4, 4> H;
67 H.setIdentity();
68 H.block<3, 1>(0, 3) << 0.1, 0, 0;
69 // Introduce a bit of pitch to make sure that we're exercising all the code.
70 H.block<3, 3>(0, 0) =
James Kuszmaul688a2b02020-02-19 18:26:33 -080071 Eigen::AngleAxis<double>(0.1, Eigen::Vector3d::UnitY()) *
James Kuszmaul5398fae2020-02-17 16:44:03 -080072 H.block<3, 3>(0, 0);
73 return H;
74}
75
76// The absolute target location to use. Not meant to correspond with a
77// particular field target.
78// TODO(james): Make more targets.
James Kuszmaul688a2b02020-02-19 18:26:33 -080079std::vector<Eigen::Matrix<double, 4, 4>> TargetLocations() {
80 std::vector<Eigen::Matrix<double, 4, 4>> locations;
James Kuszmaul5398fae2020-02-17 16:44:03 -080081 Eigen::Matrix<double, 4, 4> H;
82 H.setIdentity();
83 H.block<3, 1>(0, 3) << 10.0, 0, 0;
James Kuszmaul688a2b02020-02-19 18:26:33 -080084 locations.push_back(H);
85 H.block<3, 1>(0, 3) << -10.0, 0, 0;
James Kuszmaul5a46c8d2021-09-03 19:33:48 -070086 H.block<3, 3>(0, 0) =
87 Eigen::AngleAxis<double>(1.1, Eigen::Vector3d::UnitZ()) *
88 H.block<3, 3>(0, 0);
James Kuszmaul688a2b02020-02-19 18:26:33 -080089 locations.push_back(H);
90 return locations;
James Kuszmaul5398fae2020-02-17 16:44:03 -080091}
James Kuszmaul958b21e2020-02-26 21:51:40 -080092
James Kuszmaul8866e642022-06-10 16:00:36 -070093constexpr std::chrono::seconds kPiTimeOffset(10);
James Kuszmaul5398fae2020-02-17 16:44:03 -080094} // namespace
95
96namespace chrono = std::chrono;
James Kuszmaul5398fae2020-02-17 16:44:03 -080097using aos::monotonic_clock;
Brian Silverman1f345222020-09-24 21:14:48 -070098using frc971::control_loops::drivetrain::DrivetrainLoop;
99using frc971::control_loops::drivetrain::testing::DrivetrainSimulation;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800100
James Kuszmaul61750662021-06-21 21:32:33 -0700101class LocalizedDrivetrainTest : public frc971::testing::ControlLoopTest {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800102 protected:
103 // We must use the 2020 drivetrain config so that we don't have to deal
104 // with shifting:
105 LocalizedDrivetrainTest()
James Kuszmaul61750662021-06-21 21:32:33 -0700106 : frc971::testing::ControlLoopTest(
James Kuszmaul5398fae2020-02-17 16:44:03 -0800107 aos::configuration::ReadConfig(
108 "y2020/control_loops/drivetrain/simulation_config.json"),
Austin Schuh0debde12022-08-17 16:25:17 -0700109 GetTest2020DrivetrainConfig().dt,
110 {{BootTimestamp::epoch() + kPiTimeOffset,
111 BootTimestamp::epoch() + kPiTimeOffset,
112 BootTimestamp::epoch() + kPiTimeOffset,
113 BootTimestamp::epoch() + kPiTimeOffset,
114 BootTimestamp::epoch() + kPiTimeOffset,
115 BootTimestamp::epoch() + kPiTimeOffset, BootTimestamp::epoch()}}),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800116 roborio_(aos::configuration::GetNode(configuration(), "roborio")),
117 pi1_(aos::configuration::GetNode(configuration(), "pi1")),
118 test_event_loop_(MakeEventLoop("test", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800119 drivetrain_goal_sender_(
120 test_event_loop_->MakeSender<Goal>("/drivetrain")),
121 drivetrain_goal_fetcher_(
122 test_event_loop_->MakeFetcher<Goal>("/drivetrain")),
James Kuszmaul0a981402021-10-09 21:00:34 -0700123 drivetrain_status_fetcher_(
124 test_event_loop_
125 ->MakeFetcher<frc971::control_loops::drivetrain::Status>(
126 "/drivetrain")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800127 localizer_control_sender_(
128 test_event_loop_->MakeSender<LocalizerControl>("/drivetrain")),
James Kuszmaul688a2b02020-02-19 18:26:33 -0800129 superstructure_status_sender_(
130 test_event_loop_->MakeSender<superstructure::Status>(
131 "/superstructure")),
James Kuszmaul958b21e2020-02-26 21:51:40 -0800132 server_statistics_sender_(
133 test_event_loop_->MakeSender<aos::message_bridge::ServerStatistics>(
134 "/aos")),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800135 drivetrain_event_loop_(MakeEventLoop("drivetrain", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800136 dt_config_(GetTest2020DrivetrainConfig()),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800137 pi1_event_loop_(MakeEventLoop("test", pi1_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800138 camera_sender_(
Austin Schuh6aa77be2020-02-22 21:06:40 -0800139 pi1_event_loop_->MakeSender<ImageMatchResult>("/pi1/camera")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800140 localizer_(drivetrain_event_loop_.get(), dt_config_),
141 drivetrain_(dt_config_, drivetrain_event_loop_.get(), &localizer_),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800142 drivetrain_plant_event_loop_(MakeEventLoop("plant", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800143 drivetrain_plant_(drivetrain_plant_event_loop_.get(), dt_config_),
144 last_frame_(monotonic_now()) {
James Kuszmaul9c128122021-03-22 22:24:36 -0700145 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), roborio_), 6);
Austin Schuh87dd3832021-01-01 23:07:31 -0800146 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), pi1_), 1);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800147 set_team_id(frc971::control_loops::testing::kTeamNumber);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800148 set_battery_voltage(12.0);
149
150 if (!FLAGS_output_file.empty()) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800151 logger_event_loop_ = MakeEventLoop("logger", roborio_);
Brian Silverman1f345222020-09-24 21:14:48 -0700152 logger_ = std::make_unique<aos::logger::Logger>(logger_event_loop_.get());
James Kuszmaul0a981402021-10-09 21:00:34 -0700153 logger_->StartLoggingOnRun(FLAGS_output_file);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800154 }
155
156 test_event_loop_->MakeWatcher(
157 "/drivetrain",
158 [this](const frc971::control_loops::drivetrain::Status &) {
159 // Needs to do camera updates right after we run the control loop.
160 if (enable_cameras_) {
161 SendDelayedFrames();
162 if (last_frame_ + std::chrono::milliseconds(100) <
163 monotonic_now()) {
164 CaptureFrames();
165 last_frame_ = monotonic_now();
166 }
167 }
Brian Silverman1f345222020-09-24 21:14:48 -0700168 });
James Kuszmaul688a2b02020-02-19 18:26:33 -0800169
170 test_event_loop_->AddPhasedLoop(
171 [this](int) {
James Kuszmaul0a981402021-10-09 21:00:34 -0700172 // TODO(james): This is wrong. At a bare minimum, it is missing a boot
173 // UUID, and this is probably the wrong pattern entirely.
James Kuszmaul958b21e2020-02-26 21:51:40 -0800174 auto builder = server_statistics_sender_.MakeBuilder();
175 auto name_offset = builder.fbb()->CreateString("pi1");
176 auto node_builder = builder.MakeBuilder<aos::Node>();
177 node_builder.add_name(name_offset);
178 auto node_offset = node_builder.Finish();
179 auto connection_builder =
180 builder.MakeBuilder<aos::message_bridge::ServerConnection>();
181 connection_builder.add_node(node_offset);
182 connection_builder.add_monotonic_offset(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700183 chrono::duration_cast<chrono::nanoseconds>(kPiTimeOffset)
James Kuszmaul958b21e2020-02-26 21:51:40 -0800184 .count());
185 auto connection_offset = connection_builder.Finish();
186 auto connections_offset =
187 builder.fbb()->CreateVector(&connection_offset, 1);
188 auto statistics_builder =
189 builder.MakeBuilder<aos::message_bridge::ServerStatistics>();
190 statistics_builder.add_connections(connections_offset);
milind1f1dca32021-07-03 13:50:07 -0700191 CHECK_EQ(builder.Send(statistics_builder.Finish()),
192 aos::RawSender::Error::kOk);
James Kuszmaul958b21e2020-02-26 21:51:40 -0800193 },
194 chrono::milliseconds(500));
195
196 test_event_loop_->AddPhasedLoop(
197 [this](int) {
James Kuszmaul688a2b02020-02-19 18:26:33 -0800198 // Also use the opportunity to send out turret messages.
199 UpdateTurretPosition();
200 auto builder = superstructure_status_sender_.MakeBuilder();
201 auto turret_builder =
202 builder
203 .MakeBuilder<frc971::control_loops::
204 PotAndAbsoluteEncoderProfiledJointStatus>();
205 turret_builder.add_position(turret_position_);
206 turret_builder.add_velocity(turret_velocity_);
207 auto turret_offset = turret_builder.Finish();
208 auto status_builder = builder.MakeBuilder<superstructure::Status>();
209 status_builder.add_turret(turret_offset);
milind1f1dca32021-07-03 13:50:07 -0700210 CHECK_EQ(builder.Send(status_builder.Finish()),
211 aos::RawSender::Error::kOk);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800212 },
Yash Chainania6fe97b2021-12-15 21:01:11 -0800213 frc971::controls::kLoopFrequency);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800214
James Kuszmaul286b4282020-02-26 20:29:32 -0800215 test_event_loop_->OnRun([this]() { SetStartingPosition({3.0, 2.0, 0.0}); });
216
James Kuszmaul5398fae2020-02-17 16:44:03 -0800217 // Run for enough time to allow the gyro/imu zeroing code to run.
James Kuszmaul0a981402021-10-09 21:00:34 -0700218 RunFor(std::chrono::seconds(15));
219 CHECK(drivetrain_status_fetcher_.Fetch());
220 EXPECT_TRUE(CHECK_NOTNULL(drivetrain_status_fetcher_->zeroing())->zeroed());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800221 }
222
223 virtual ~LocalizedDrivetrainTest() override {}
224
225 void SetStartingPosition(const Eigen::Matrix<double, 3, 1> &xytheta) {
226 *drivetrain_plant_.mutable_state() << xytheta.x(), xytheta.y(),
227 xytheta(2, 0), 0.0, 0.0;
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700228 Eigen::Matrix<double, Localizer::HybridEkf::kNStates, 1> localizer_state;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800229 localizer_state.setZero();
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700230 localizer_state.block<3, 1>(0, 0) = xytheta;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800231 localizer_.Reset(monotonic_now(), localizer_state);
232 }
233
James Kuszmaul0a981402021-10-09 21:00:34 -0700234 void VerifyNearGoal(double eps = 1e-2) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800235 drivetrain_goal_fetcher_.Fetch();
236 EXPECT_NEAR(drivetrain_goal_fetcher_->left_goal(),
237 drivetrain_plant_.GetLeftPosition(), eps);
238 EXPECT_NEAR(drivetrain_goal_fetcher_->right_goal(),
239 drivetrain_plant_.GetRightPosition(), eps);
240 }
241
James Kuszmaul688a2b02020-02-19 18:26:33 -0800242 ::testing::AssertionResult IsNear(double expected, double actual,
243 double epsilon) {
244 if (std::abs(expected - actual) < epsilon) {
245 return ::testing::AssertionSuccess();
246 } else {
247 return ::testing::AssertionFailure()
248 << "Expected " << expected << " but got " << actual
249 << " with a max difference of " << epsilon
250 << " and an actual difference of " << std::abs(expected - actual);
251 }
252 }
253 ::testing::AssertionResult VerifyEstimatorAccurate(double eps) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800254 const Eigen::Matrix<double, 5, 1> true_state = drivetrain_plant_.state();
James Kuszmaul688a2b02020-02-19 18:26:33 -0800255 ::testing::AssertionResult result(true);
256 if (!(result = IsNear(localizer_.x(), true_state(0), eps))) {
257 return result;
258 }
259 if (!(result = IsNear(localizer_.y(), true_state(1), eps))) {
260 return result;
261 }
262 if (!(result = IsNear(localizer_.theta(), true_state(2), eps))) {
263 return result;
264 }
265 if (!(result = IsNear(localizer_.left_velocity(), true_state(3), eps))) {
266 return result;
267 }
268 if (!(result = IsNear(localizer_.right_velocity(), true_state(4), eps))) {
269 return result;
270 }
271 return result;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800272 }
273
274 // Goes through and captures frames on the camera(s), queueing them up to be
275 // sent by SendDelayedFrames().
276 void CaptureFrames() {
277 const frc971::control_loops::Pose robot_pose(
278 {drivetrain_plant_.GetPosition().x(),
279 drivetrain_plant_.GetPosition().y(), 0.0},
280 drivetrain_plant_.state()(2, 0));
281 std::unique_ptr<ImageMatchResultT> frame(new ImageMatchResultT());
282
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800283 for (const auto &H_field_target : TargetLocations()) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800284 std::unique_ptr<CameraPoseT> camera_target(new CameraPoseT());
285
286 camera_target->field_to_target.reset(new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800287 camera_target->field_to_target->data = MatrixToVector(H_field_target);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800288
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800289 Eigen::Matrix<double, 4, 4> H_turret_camera =
James Kuszmaul688a2b02020-02-19 18:26:33 -0800290 Eigen::Matrix<double, 4, 4>::Identity();
291 if (is_turreted_) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800292 H_turret_camera = frc971::control_loops::TransformationMatrixForYaw(
James Kuszmaul688a2b02020-02-19 18:26:33 -0800293 turret_position_) *
294 CameraTurretTransformation();
295 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800296
297 // TODO(james): Use non-zero turret angles.
298 camera_target->camera_to_target.reset(new TransformationMatrixT());
James Kuszmaulaca88782021-04-24 16:48:45 -0700299 camera_target->camera_to_target->data = MatrixToVector(
300 (robot_pose.AsTransformationMatrix() * TurretRobotTransformation() *
301 H_turret_camera * camera_calibration_offset_)
302 .inverse() *
303 H_field_target);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800304
305 frame->camera_poses.emplace_back(std::move(camera_target));
306 }
307
308 frame->image_monotonic_timestamp_ns =
309 chrono::duration_cast<chrono::nanoseconds>(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800310 event_loop_factory()
311 ->GetNodeEventLoopFactory(pi1_)
312 ->monotonic_now()
313 .time_since_epoch())
James Kuszmaul5398fae2020-02-17 16:44:03 -0800314 .count();
315 frame->camera_calibration.reset(new CameraCalibrationT());
316 {
317 frame->camera_calibration->fixed_extrinsics.reset(
318 new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800319 TransformationMatrixT *H_robot_turret =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800320 frame->camera_calibration->fixed_extrinsics.get();
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800321 H_robot_turret->data = MatrixToVector(TurretRobotTransformation());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800322 }
James Kuszmaul688a2b02020-02-19 18:26:33 -0800323
324 if (is_turreted_) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800325 frame->camera_calibration->turret_extrinsics.reset(
326 new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800327 TransformationMatrixT *H_turret_camera =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800328 frame->camera_calibration->turret_extrinsics.get();
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800329 H_turret_camera->data = MatrixToVector(CameraTurretTransformation());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800330 }
331
332 camera_delay_queue_.emplace(monotonic_now(), std::move(frame));
333 }
334
335 // Actually sends out all the camera frames.
336 void SendDelayedFrames() {
337 const std::chrono::milliseconds camera_latency(150);
338 while (!camera_delay_queue_.empty() &&
339 std::get<0>(camera_delay_queue_.front()) <
340 monotonic_now() - camera_latency) {
341 auto builder = camera_sender_.MakeBuilder();
milind1f1dca32021-07-03 13:50:07 -0700342 ASSERT_EQ(
343 builder.Send(ImageMatchResult::Pack(
344 *builder.fbb(), std::get<1>(camera_delay_queue_.front()).get())),
345 aos::RawSender::Error::kOk);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800346 camera_delay_queue_.pop();
347 }
348 }
349
Austin Schuh6aa77be2020-02-22 21:06:40 -0800350 const aos::Node *const roborio_;
351 const aos::Node *const pi1_;
352
James Kuszmaul5398fae2020-02-17 16:44:03 -0800353 std::unique_ptr<aos::EventLoop> test_event_loop_;
354 aos::Sender<Goal> drivetrain_goal_sender_;
355 aos::Fetcher<Goal> drivetrain_goal_fetcher_;
James Kuszmaul0a981402021-10-09 21:00:34 -0700356 aos::Fetcher<frc971::control_loops::drivetrain::Status>
357 drivetrain_status_fetcher_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800358 aos::Sender<LocalizerControl> localizer_control_sender_;
James Kuszmaul688a2b02020-02-19 18:26:33 -0800359 aos::Sender<superstructure::Status> superstructure_status_sender_;
James Kuszmaul958b21e2020-02-26 21:51:40 -0800360 aos::Sender<aos::message_bridge::ServerStatistics> server_statistics_sender_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800361
362 std::unique_ptr<aos::EventLoop> drivetrain_event_loop_;
Brian Silverman1f345222020-09-24 21:14:48 -0700363 const frc971::control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800364
Austin Schuh6aa77be2020-02-22 21:06:40 -0800365 std::unique_ptr<aos::EventLoop> pi1_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800366 aos::Sender<ImageMatchResult> camera_sender_;
367
368 Localizer localizer_;
369 DrivetrainLoop drivetrain_;
370
371 std::unique_ptr<aos::EventLoop> drivetrain_plant_event_loop_;
372 DrivetrainSimulation drivetrain_plant_;
373 monotonic_clock::time_point last_frame_;
374
375 // A queue of camera frames so that we can add a time delay to the data
376 // coming from the cameras.
377 std::queue<std::tuple<aos::monotonic_clock::time_point,
378 std::unique_ptr<ImageMatchResultT>>>
379 camera_delay_queue_;
380
James Kuszmaulaca88782021-04-24 16:48:45 -0700381 // Offset to add to the camera for actually taking the images, to simulate an
382 // inaccurate calibration.
383 Eigen::Matrix<double, 4, 4> camera_calibration_offset_ =
384 Eigen::Matrix<double, 4, 4>::Identity();
385
James Kuszmaul5398fae2020-02-17 16:44:03 -0800386 void set_enable_cameras(bool enable) { enable_cameras_ = enable; }
James Kuszmaul688a2b02020-02-19 18:26:33 -0800387 void set_camera_is_turreted(bool turreted) { is_turreted_ = turreted; }
388
389 void set_turret(double position, double velocity) {
390 turret_position_ = position;
391 turret_velocity_ = velocity;
392 }
393
394 void SendGoal(double left, double right) {
395 auto builder = drivetrain_goal_sender_.MakeBuilder();
396
397 Goal::Builder drivetrain_builder = builder.MakeBuilder<Goal>();
398 drivetrain_builder.add_controller_type(
399 frc971::control_loops::drivetrain::ControllerType::MOTION_PROFILE);
400 drivetrain_builder.add_left_goal(left);
401 drivetrain_builder.add_right_goal(right);
402
milind1f1dca32021-07-03 13:50:07 -0700403 EXPECT_EQ(builder.Send(drivetrain_builder.Finish()),
404 aos::RawSender::Error::kOk);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800405 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800406
407 private:
James Kuszmaul688a2b02020-02-19 18:26:33 -0800408 void UpdateTurretPosition() {
409 turret_position_ +=
410 turret_velocity_ *
411 aos::time::DurationInSeconds(monotonic_now() - last_turret_update_);
412 last_turret_update_ = monotonic_now();
413 }
414
James Kuszmaul5398fae2020-02-17 16:44:03 -0800415 bool enable_cameras_ = false;
James Kuszmaul688a2b02020-02-19 18:26:33 -0800416 // Whether to make the camera be on the turret or not.
417 bool is_turreted_ = true;
418
419 // The time at which we last incremented turret_position_.
420 monotonic_clock::time_point last_turret_update_ = monotonic_clock::min_time;
421 // Current turret position and velocity. These are set directly by the user in
422 // the test, and if velocity is non-zero, then we will automatically increment
423 // turret_position_ with every timestep.
424 double turret_position_ = 0.0; // rad
425 double turret_velocity_ = 0.0; // rad / sec
James Kuszmaul5398fae2020-02-17 16:44:03 -0800426
427 std::unique_ptr<aos::EventLoop> logger_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800428 std::unique_ptr<aos::logger::Logger> logger_;
429};
430
431// Tests that no camera updates, combined with a perfect model, results in no
432// error.
433TEST_F(LocalizedDrivetrainTest, NoCameraUpdate) {
434 SetEnabled(true);
435 set_enable_cameras(false);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800436 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800437
James Kuszmaul688a2b02020-02-19 18:26:33 -0800438 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800439
James Kuszmaul0a981402021-10-09 21:00:34 -0700440 RunFor(chrono::seconds(10));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800441 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700442 EXPECT_TRUE(VerifyEstimatorAccurate(5e-3));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800443}
444
James Kuszmaul7f55f072020-03-01 10:21:26 -0800445// Tests that we can drive in a straight line and have things estimate
446// correctly.
447TEST_F(LocalizedDrivetrainTest, NoCameraUpdateStraightLine) {
448 SetEnabled(true);
449 set_enable_cameras(false);
450 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
451
452 SendGoal(1.0, 1.0);
453
James Kuszmaul0a981402021-10-09 21:00:34 -0700454 RunFor(chrono::seconds(3));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800455 VerifyNearGoal();
456 // Due to accelerometer drift, the straight-line driving tends to be less
457 // accurate...
Austin Schuhcadb3292021-01-23 20:24:17 -0800458 EXPECT_TRUE(VerifyEstimatorAccurate(0.15));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800459}
460
James Kuszmaul688a2b02020-02-19 18:26:33 -0800461// Tests that camera updates with a perfect models results in no errors.
James Kuszmaul5398fae2020-02-17 16:44:03 -0800462TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdate) {
463 SetEnabled(true);
464 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800465 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800466
James Kuszmaul688a2b02020-02-19 18:26:33 -0800467 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800468
James Kuszmaul5398fae2020-02-17 16:44:03 -0800469 RunFor(chrono::seconds(3));
470 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700471 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800472}
473
James Kuszmaulaca88782021-04-24 16:48:45 -0700474// Tests that camera updates with a perfect model but incorrect camera pitch
475// results in no errors.
476TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdateWithBadPitch) {
477 // Introduce some camera pitch.
478 camera_calibration_offset_.template block<3, 3>(0, 0) =
479 Eigen::AngleAxis<double>(0.1, Eigen::Vector3d::UnitY())
480 .toRotationMatrix();
481 SetEnabled(true);
482 set_enable_cameras(true);
483 set_camera_is_turreted(true);
484
485 SendGoal(-1.0, 1.0);
486
487 RunFor(chrono::seconds(3));
488 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700489 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaulaca88782021-04-24 16:48:45 -0700490}
491
James Kuszmaul688a2b02020-02-19 18:26:33 -0800492// Tests that camera updates with a constant initial error in the position
James Kuszmaul5398fae2020-02-17 16:44:03 -0800493// results in convergence.
494TEST_F(LocalizedDrivetrainTest, InitialPositionError) {
495 SetEnabled(true);
496 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800497 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800498 drivetrain_plant_.mutable_state()->topRows(3) +=
499 Eigen::Vector3d(0.1, 0.1, 0.01);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800500
James Kuszmaul688a2b02020-02-19 18:26:33 -0800501 // Confirm that some translational movement does get handled correctly.
502 SendGoal(-0.9, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800503
James Kuszmaul5398fae2020-02-17 16:44:03 -0800504 // Give the filters enough time to converge.
505 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700506 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800507 EXPECT_TRUE(VerifyEstimatorAccurate(4e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800508}
509
510// Tests that camera updates using a non-turreted camera work.
511TEST_F(LocalizedDrivetrainTest, InitialPositionErrorNoTurret) {
512 SetEnabled(true);
513 set_enable_cameras(true);
514 set_camera_is_turreted(false);
515 drivetrain_plant_.mutable_state()->topRows(3) +=
516 Eigen::Vector3d(0.1, 0.1, 0.01);
517
518 SendGoal(-1.0, 1.0);
519
520 // Give the filters enough time to converge.
521 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700522 VerifyNearGoal(5e-2);
Austin Schuheb718632021-10-22 22:32:57 -0700523 EXPECT_TRUE(VerifyEstimatorAccurate(0.1));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800524}
525
526// Tests that we are able to handle a constant, non-zero turret angle.
527TEST_F(LocalizedDrivetrainTest, NonZeroTurret) {
528 SetEnabled(true);
529 set_enable_cameras(true);
530 set_camera_is_turreted(true);
531 set_turret(1.0, 0.0);
532 drivetrain_plant_.mutable_state()->topRows(3) +=
533 Eigen::Vector3d(0.1, 0.1, 0.0);
534
535 SendGoal(-1.0, 1.0);
536
537 // Give the filters enough time to converge.
538 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700539 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800540 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800541}
542
543// Tests that we are able to handle a constant velocity turret.
544TEST_F(LocalizedDrivetrainTest, MovingTurret) {
545 SetEnabled(true);
546 set_enable_cameras(true);
547 set_camera_is_turreted(true);
548 set_turret(0.0, 0.2);
549 drivetrain_plant_.mutable_state()->topRows(3) +=
550 Eigen::Vector3d(0.1, 0.1, 0.0);
551
552 SendGoal(-1.0, 1.0);
553
554 // Give the filters enough time to converge.
555 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700556 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800557 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800558}
559
560// Tests that we reject camera measurements when the turret is spinning too
561// fast.
562TEST_F(LocalizedDrivetrainTest, TooFastTurret) {
563 SetEnabled(true);
564 set_enable_cameras(true);
565 set_camera_is_turreted(true);
566 set_turret(0.0, -10.0);
567 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
568 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
569
570 SendGoal(-1.0, 1.0);
571
572 RunFor(chrono::seconds(10));
573 EXPECT_FALSE(VerifyEstimatorAccurate(1e-3));
574 // If we remove the disturbance, we should now be correct.
575 drivetrain_plant_.mutable_state()->topRows(3) -= disturbance;
James Kuszmaul0a981402021-10-09 21:00:34 -0700576 VerifyNearGoal(5e-2);
577 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800578}
579
580// Tests that we don't reject camera measurements when the turret is spinning
581// too fast but we aren't using a camera attached to the turret.
582TEST_F(LocalizedDrivetrainTest, TooFastTurretDoesntAffectFixedCamera) {
583 SetEnabled(true);
584 set_enable_cameras(true);
585 set_camera_is_turreted(false);
586 set_turret(0.0, -10.0);
587 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
588 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
589
590 SendGoal(-1.0, 1.0);
591
592 RunFor(chrono::seconds(10));
593 VerifyNearGoal(5e-3);
Austin Schuheb718632021-10-22 22:32:57 -0700594 EXPECT_TRUE(VerifyEstimatorAccurate(5e-2));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800595}
596
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700597// Tests that we don't blow up if we stop getting updates for an extended period
598// of time and fall behind on fetching fron the cameras.
599TEST_F(LocalizedDrivetrainTest, FetchersHandleTimeGap) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700600 set_enable_cameras(false);
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700601 set_send_delay(std::chrono::seconds(0));
602 event_loop_factory()->set_network_delay(std::chrono::nanoseconds(1));
603 test_event_loop_
604 ->AddTimer([this]() { drivetrain_plant_.set_send_messages(false); })
605 ->Setup(test_event_loop_->monotonic_now());
606 test_event_loop_->AddPhasedLoop(
607 [this](int) {
608 auto builder = camera_sender_.MakeBuilder();
609 ImageMatchResultT image;
milind1f1dca32021-07-03 13:50:07 -0700610 ASSERT_EQ(builder.Send(ImageMatchResult::Pack(*builder.fbb(), &image)),
611 aos::RawSender::Error::kOk);
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700612 },
milind945708b2021-07-03 13:30:15 -0700613 std::chrono::milliseconds(40));
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700614 test_event_loop_
615 ->AddTimer([this]() {
616 drivetrain_plant_.set_send_messages(true);
617 SimulateSensorReset();
618 })
619 ->Setup(test_event_loop_->monotonic_now() + std::chrono::seconds(10));
620
621 RunFor(chrono::seconds(20));
622}
623
James Kuszmaul5398fae2020-02-17 16:44:03 -0800624} // namespace testing
625} // namespace drivetrain
626} // namespace control_loops
627} // namespace y2020