blob: aac8f75741fcd0e65e683c9162ac9af6f79c4b73 [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"
Austin Schuh87dd3832021-01-01 23:07:31 -08008#include "aos/network/testing_time_converter.h"
James Kuszmaul61750662021-06-21 21:32:33 -07009#include "frc971/control_loops/control_loop_test.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -080010#include "frc971/control_loops/drivetrain/drivetrain.h"
11#include "frc971/control_loops/drivetrain/drivetrain_test_lib.h"
12#include "frc971/control_loops/team_number_test_environment.h"
James Kuszmaul61750662021-06-21 21:32:33 -070013#include "gtest/gtest.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -080014#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
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
Austin Schuhbe69cf32020-08-27 11:38:33 -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"),
110 GetTest2020DrivetrainConfig().dt),
Austin Schuh87dd3832021-01-01 23:07:31 -0800111 time_converter_(aos::configuration::NodesCount(configuration())),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800112 roborio_(aos::configuration::GetNode(configuration(), "roborio")),
113 pi1_(aos::configuration::GetNode(configuration(), "pi1")),
114 test_event_loop_(MakeEventLoop("test", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800115 drivetrain_goal_sender_(
116 test_event_loop_->MakeSender<Goal>("/drivetrain")),
117 drivetrain_goal_fetcher_(
118 test_event_loop_->MakeFetcher<Goal>("/drivetrain")),
James Kuszmaul0a981402021-10-09 21:00:34 -0700119 drivetrain_status_fetcher_(
120 test_event_loop_
121 ->MakeFetcher<frc971::control_loops::drivetrain::Status>(
122 "/drivetrain")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800123 localizer_control_sender_(
124 test_event_loop_->MakeSender<LocalizerControl>("/drivetrain")),
James Kuszmaul688a2b02020-02-19 18:26:33 -0800125 superstructure_status_sender_(
126 test_event_loop_->MakeSender<superstructure::Status>(
127 "/superstructure")),
James Kuszmaul958b21e2020-02-26 21:51:40 -0800128 server_statistics_sender_(
129 test_event_loop_->MakeSender<aos::message_bridge::ServerStatistics>(
130 "/aos")),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800131 drivetrain_event_loop_(MakeEventLoop("drivetrain", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800132 dt_config_(GetTest2020DrivetrainConfig()),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800133 pi1_event_loop_(MakeEventLoop("test", pi1_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800134 camera_sender_(
Austin Schuh6aa77be2020-02-22 21:06:40 -0800135 pi1_event_loop_->MakeSender<ImageMatchResult>("/pi1/camera")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800136 localizer_(drivetrain_event_loop_.get(), dt_config_),
137 drivetrain_(dt_config_, drivetrain_event_loop_.get(), &localizer_),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800138 drivetrain_plant_event_loop_(MakeEventLoop("plant", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800139 drivetrain_plant_(drivetrain_plant_event_loop_.get(), dt_config_),
140 last_frame_(monotonic_now()) {
Austin Schuh87dd3832021-01-01 23:07:31 -0800141 event_loop_factory()->SetTimeConverter(&time_converter_);
James Kuszmaul9c128122021-03-22 22:24:36 -0700142 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), roborio_), 6);
Austin Schuh87dd3832021-01-01 23:07:31 -0800143 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), pi1_), 1);
Austin Schuh66168842021-08-17 19:42:21 -0700144 time_converter_.AddMonotonic({BootTimestamp::epoch() + kPiTimeOffset,
145 BootTimestamp::epoch() + kPiTimeOffset,
146 BootTimestamp::epoch() + kPiTimeOffset,
147 BootTimestamp::epoch() + kPiTimeOffset,
148 BootTimestamp::epoch() + kPiTimeOffset,
149 BootTimestamp::epoch() + kPiTimeOffset,
150 BootTimestamp::epoch()});
James Kuszmaul5398fae2020-02-17 16:44:03 -0800151 set_team_id(frc971::control_loops::testing::kTeamNumber);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800152 set_battery_voltage(12.0);
153
154 if (!FLAGS_output_file.empty()) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800155 logger_event_loop_ = MakeEventLoop("logger", roborio_);
Brian Silverman1f345222020-09-24 21:14:48 -0700156 logger_ = std::make_unique<aos::logger::Logger>(logger_event_loop_.get());
James Kuszmaul0a981402021-10-09 21:00:34 -0700157 logger_->StartLoggingOnRun(FLAGS_output_file);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800158 }
159
160 test_event_loop_->MakeWatcher(
161 "/drivetrain",
162 [this](const frc971::control_loops::drivetrain::Status &) {
163 // Needs to do camera updates right after we run the control loop.
164 if (enable_cameras_) {
165 SendDelayedFrames();
166 if (last_frame_ + std::chrono::milliseconds(100) <
167 monotonic_now()) {
168 CaptureFrames();
169 last_frame_ = monotonic_now();
170 }
171 }
Brian Silverman1f345222020-09-24 21:14:48 -0700172 });
James Kuszmaul688a2b02020-02-19 18:26:33 -0800173
174 test_event_loop_->AddPhasedLoop(
175 [this](int) {
James Kuszmaul0a981402021-10-09 21:00:34 -0700176 // TODO(james): This is wrong. At a bare minimum, it is missing a boot
177 // UUID, and this is probably the wrong pattern entirely.
James Kuszmaul958b21e2020-02-26 21:51:40 -0800178 auto builder = server_statistics_sender_.MakeBuilder();
179 auto name_offset = builder.fbb()->CreateString("pi1");
180 auto node_builder = builder.MakeBuilder<aos::Node>();
181 node_builder.add_name(name_offset);
182 auto node_offset = node_builder.Finish();
183 auto connection_builder =
184 builder.MakeBuilder<aos::message_bridge::ServerConnection>();
185 connection_builder.add_node(node_offset);
186 connection_builder.add_monotonic_offset(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700187 chrono::duration_cast<chrono::nanoseconds>(kPiTimeOffset)
James Kuszmaul958b21e2020-02-26 21:51:40 -0800188 .count());
189 auto connection_offset = connection_builder.Finish();
190 auto connections_offset =
191 builder.fbb()->CreateVector(&connection_offset, 1);
192 auto statistics_builder =
193 builder.MakeBuilder<aos::message_bridge::ServerStatistics>();
194 statistics_builder.add_connections(connections_offset);
195 builder.Send(statistics_builder.Finish());
196 },
197 chrono::milliseconds(500));
198
199 test_event_loop_->AddPhasedLoop(
200 [this](int) {
James Kuszmaul688a2b02020-02-19 18:26:33 -0800201 // Also use the opportunity to send out turret messages.
202 UpdateTurretPosition();
203 auto builder = superstructure_status_sender_.MakeBuilder();
204 auto turret_builder =
205 builder
206 .MakeBuilder<frc971::control_loops::
207 PotAndAbsoluteEncoderProfiledJointStatus>();
208 turret_builder.add_position(turret_position_);
209 turret_builder.add_velocity(turret_velocity_);
210 auto turret_offset = turret_builder.Finish();
211 auto status_builder = builder.MakeBuilder<superstructure::Status>();
212 status_builder.add_turret(turret_offset);
213 builder.Send(status_builder.Finish());
214 },
215 chrono::milliseconds(5));
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();
344 ASSERT_TRUE(builder.Send(ImageMatchResult::Pack(
345 *builder.fbb(), std::get<1>(camera_delay_queue_.front()).get())));
346 camera_delay_queue_.pop();
347 }
348 }
349
Austin Schuh87dd3832021-01-01 23:07:31 -0800350 aos::message_bridge::TestingTimeConverter time_converter_;
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
405 EXPECT_TRUE(builder.Send(drivetrain_builder.Finish()));
406 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800407
408 private:
James Kuszmaul688a2b02020-02-19 18:26:33 -0800409 void UpdateTurretPosition() {
410 turret_position_ +=
411 turret_velocity_ *
412 aos::time::DurationInSeconds(monotonic_now() - last_turret_update_);
413 last_turret_update_ = monotonic_now();
414 }
415
James Kuszmaul5398fae2020-02-17 16:44:03 -0800416 bool enable_cameras_ = false;
James Kuszmaul688a2b02020-02-19 18:26:33 -0800417 // Whether to make the camera be on the turret or not.
418 bool is_turreted_ = true;
419
420 // The time at which we last incremented turret_position_.
421 monotonic_clock::time_point last_turret_update_ = monotonic_clock::min_time;
422 // Current turret position and velocity. These are set directly by the user in
423 // the test, and if velocity is non-zero, then we will automatically increment
424 // turret_position_ with every timestep.
425 double turret_position_ = 0.0; // rad
426 double turret_velocity_ = 0.0; // rad / sec
James Kuszmaul5398fae2020-02-17 16:44:03 -0800427
428 std::unique_ptr<aos::EventLoop> logger_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800429 std::unique_ptr<aos::logger::Logger> logger_;
430};
431
432// Tests that no camera updates, combined with a perfect model, results in no
433// error.
434TEST_F(LocalizedDrivetrainTest, NoCameraUpdate) {
435 SetEnabled(true);
436 set_enable_cameras(false);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800437 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800438
James Kuszmaul688a2b02020-02-19 18:26:33 -0800439 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800440
James Kuszmaul0a981402021-10-09 21:00:34 -0700441 RunFor(chrono::seconds(10));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800442 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700443 EXPECT_TRUE(VerifyEstimatorAccurate(5e-3));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800444}
445
James Kuszmaul7f55f072020-03-01 10:21:26 -0800446// Tests that we can drive in a straight line and have things estimate
447// correctly.
448TEST_F(LocalizedDrivetrainTest, NoCameraUpdateStraightLine) {
449 SetEnabled(true);
450 set_enable_cameras(false);
451 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
452
453 SendGoal(1.0, 1.0);
454
James Kuszmaul0a981402021-10-09 21:00:34 -0700455 RunFor(chrono::seconds(3));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800456 VerifyNearGoal();
457 // Due to accelerometer drift, the straight-line driving tends to be less
458 // accurate...
Austin Schuhcadb3292021-01-23 20:24:17 -0800459 EXPECT_TRUE(VerifyEstimatorAccurate(0.15));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800460}
461
James Kuszmaul688a2b02020-02-19 18:26:33 -0800462// Tests that camera updates with a perfect models results in no errors.
James Kuszmaul5398fae2020-02-17 16:44:03 -0800463TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdate) {
464 SetEnabled(true);
465 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800466 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800467
James Kuszmaul688a2b02020-02-19 18:26:33 -0800468 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800469
James Kuszmaul5398fae2020-02-17 16:44:03 -0800470 RunFor(chrono::seconds(3));
471 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700472 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800473}
474
James Kuszmaulaca88782021-04-24 16:48:45 -0700475// Tests that camera updates with a perfect model but incorrect camera pitch
476// results in no errors.
477TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdateWithBadPitch) {
478 // Introduce some camera pitch.
479 camera_calibration_offset_.template block<3, 3>(0, 0) =
480 Eigen::AngleAxis<double>(0.1, Eigen::Vector3d::UnitY())
481 .toRotationMatrix();
482 SetEnabled(true);
483 set_enable_cameras(true);
484 set_camera_is_turreted(true);
485
486 SendGoal(-1.0, 1.0);
487
488 RunFor(chrono::seconds(3));
489 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700490 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaulaca88782021-04-24 16:48:45 -0700491}
492
James Kuszmaul688a2b02020-02-19 18:26:33 -0800493// Tests that camera updates with a constant initial error in the position
James Kuszmaul5398fae2020-02-17 16:44:03 -0800494// results in convergence.
495TEST_F(LocalizedDrivetrainTest, InitialPositionError) {
496 SetEnabled(true);
497 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800498 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800499 drivetrain_plant_.mutable_state()->topRows(3) +=
500 Eigen::Vector3d(0.1, 0.1, 0.01);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800501
James Kuszmaul688a2b02020-02-19 18:26:33 -0800502 // Confirm that some translational movement does get handled correctly.
503 SendGoal(-0.9, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800504
James Kuszmaul5398fae2020-02-17 16:44:03 -0800505 // Give the filters enough time to converge.
506 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700507 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800508 EXPECT_TRUE(VerifyEstimatorAccurate(4e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800509}
510
511// Tests that camera updates using a non-turreted camera work.
512TEST_F(LocalizedDrivetrainTest, InitialPositionErrorNoTurret) {
513 SetEnabled(true);
514 set_enable_cameras(true);
515 set_camera_is_turreted(false);
516 drivetrain_plant_.mutable_state()->topRows(3) +=
517 Eigen::Vector3d(0.1, 0.1, 0.01);
518
519 SendGoal(-1.0, 1.0);
520
521 // Give the filters enough time to converge.
522 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700523 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800524 EXPECT_TRUE(VerifyEstimatorAccurate(4e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800525}
526
527// Tests that we are able to handle a constant, non-zero turret angle.
528TEST_F(LocalizedDrivetrainTest, NonZeroTurret) {
529 SetEnabled(true);
530 set_enable_cameras(true);
531 set_camera_is_turreted(true);
532 set_turret(1.0, 0.0);
533 drivetrain_plant_.mutable_state()->topRows(3) +=
534 Eigen::Vector3d(0.1, 0.1, 0.0);
535
536 SendGoal(-1.0, 1.0);
537
538 // Give the filters enough time to converge.
539 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700540 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800541 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800542}
543
544// Tests that we are able to handle a constant velocity turret.
545TEST_F(LocalizedDrivetrainTest, MovingTurret) {
546 SetEnabled(true);
547 set_enable_cameras(true);
548 set_camera_is_turreted(true);
549 set_turret(0.0, 0.2);
550 drivetrain_plant_.mutable_state()->topRows(3) +=
551 Eigen::Vector3d(0.1, 0.1, 0.0);
552
553 SendGoal(-1.0, 1.0);
554
555 // Give the filters enough time to converge.
556 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700557 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800558 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800559}
560
561// Tests that we reject camera measurements when the turret is spinning too
562// fast.
563TEST_F(LocalizedDrivetrainTest, TooFastTurret) {
564 SetEnabled(true);
565 set_enable_cameras(true);
566 set_camera_is_turreted(true);
567 set_turret(0.0, -10.0);
568 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
569 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
570
571 SendGoal(-1.0, 1.0);
572
573 RunFor(chrono::seconds(10));
574 EXPECT_FALSE(VerifyEstimatorAccurate(1e-3));
575 // If we remove the disturbance, we should now be correct.
576 drivetrain_plant_.mutable_state()->topRows(3) -= disturbance;
James Kuszmaul0a981402021-10-09 21:00:34 -0700577 VerifyNearGoal(5e-2);
578 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800579}
580
581// Tests that we don't reject camera measurements when the turret is spinning
582// too fast but we aren't using a camera attached to the turret.
583TEST_F(LocalizedDrivetrainTest, TooFastTurretDoesntAffectFixedCamera) {
584 SetEnabled(true);
585 set_enable_cameras(true);
586 set_camera_is_turreted(false);
587 set_turret(0.0, -10.0);
588 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
589 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
590
591 SendGoal(-1.0, 1.0);
592
593 RunFor(chrono::seconds(10));
594 VerifyNearGoal(5e-3);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800595 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800596}
597
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700598// Tests that we don't blow up if we stop getting updates for an extended period
599// of time and fall behind on fetching fron the cameras.
600TEST_F(LocalizedDrivetrainTest, FetchersHandleTimeGap) {
601 set_enable_cameras(true);
602 set_send_delay(std::chrono::seconds(0));
603 event_loop_factory()->set_network_delay(std::chrono::nanoseconds(1));
604 test_event_loop_
605 ->AddTimer([this]() { drivetrain_plant_.set_send_messages(false); })
606 ->Setup(test_event_loop_->monotonic_now());
607 test_event_loop_->AddPhasedLoop(
608 [this](int) {
609 auto builder = camera_sender_.MakeBuilder();
610 ImageMatchResultT image;
611 ASSERT_TRUE(
612 builder.Send(ImageMatchResult::Pack(*builder.fbb(), &image)));
613 },
milind945708b2021-07-03 13:30:15 -0700614 std::chrono::milliseconds(40));
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700615 test_event_loop_
616 ->AddTimer([this]() {
617 drivetrain_plant_.set_send_messages(true);
618 SimulateSensorReset();
619 })
620 ->Setup(test_event_loop_->monotonic_now() + std::chrono::seconds(10));
621
622 RunFor(chrono::seconds(20));
623}
624
James Kuszmaul5398fae2020-02-17 16:44:03 -0800625} // namespace testing
626} // namespace drivetrain
627} // namespace control_loops
628} // namespace y2020