blob: e509241987061a29939afa86a828a5b7afe18cde [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")),
Austin Schuhd027bf52024-05-12 22:24:12 -0700116 drivetrain_event_loop_(MakeEventLoop("drivetrain", roborio_)),
117 dt_config_(GetTest2020DrivetrainConfig()),
118 pi1_event_loop_(MakeEventLoop("test", pi1_)),
119 camera_sender_(
120 pi1_event_loop_->MakeSender<ImageMatchResult>("/pi1/camera")),
121 localizer_(drivetrain_event_loop_.get(), dt_config_),
122 drivetrain_(dt_config_, drivetrain_event_loop_.get(), &localizer_),
123 drivetrain_plant_event_loop_(MakeEventLoop("plant", roborio_)),
124 drivetrain_plant_(drivetrain_plant_event_loop_.get(), dt_config_),
125 last_frame_(monotonic_now()),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800126 test_event_loop_(MakeEventLoop("test", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800127 drivetrain_goal_sender_(
128 test_event_loop_->MakeSender<Goal>("/drivetrain")),
129 drivetrain_goal_fetcher_(
130 test_event_loop_->MakeFetcher<Goal>("/drivetrain")),
James Kuszmaul0a981402021-10-09 21:00:34 -0700131 drivetrain_status_fetcher_(
132 test_event_loop_
133 ->MakeFetcher<frc971::control_loops::drivetrain::Status>(
134 "/drivetrain")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800135 localizer_control_sender_(
136 test_event_loop_->MakeSender<LocalizerControl>("/drivetrain")),
James Kuszmaul688a2b02020-02-19 18:26:33 -0800137 superstructure_status_sender_(
138 test_event_loop_->MakeSender<superstructure::Status>(
139 "/superstructure")),
James Kuszmaul958b21e2020-02-26 21:51:40 -0800140 server_statistics_sender_(
141 test_event_loop_->MakeSender<aos::message_bridge::ServerStatistics>(
Austin Schuhd027bf52024-05-12 22:24:12 -0700142 "/aos")) {
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());
Austin Schuh6bdcc372024-06-27 14:49:11 -0700218 CHECK(drivetrain_status_fetcher_->zeroing() != nullptr);
219 EXPECT_TRUE(drivetrain_status_fetcher_->zeroing()->zeroed());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800220 }
221
222 virtual ~LocalizedDrivetrainTest() override {}
223
224 void SetStartingPosition(const Eigen::Matrix<double, 3, 1> &xytheta) {
225 *drivetrain_plant_.mutable_state() << xytheta.x(), xytheta.y(),
226 xytheta(2, 0), 0.0, 0.0;
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700227 Eigen::Matrix<double, Localizer::HybridEkf::kNStates, 1> localizer_state;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800228 localizer_state.setZero();
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700229 localizer_state.block<3, 1>(0, 0) = xytheta;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800230 localizer_.Reset(monotonic_now(), localizer_state);
231 }
232
James Kuszmaul0a981402021-10-09 21:00:34 -0700233 void VerifyNearGoal(double eps = 1e-2) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800234 drivetrain_goal_fetcher_.Fetch();
235 EXPECT_NEAR(drivetrain_goal_fetcher_->left_goal(),
236 drivetrain_plant_.GetLeftPosition(), eps);
237 EXPECT_NEAR(drivetrain_goal_fetcher_->right_goal(),
238 drivetrain_plant_.GetRightPosition(), eps);
239 }
240
James Kuszmaul688a2b02020-02-19 18:26:33 -0800241 ::testing::AssertionResult IsNear(double expected, double actual,
242 double epsilon) {
243 if (std::abs(expected - actual) < epsilon) {
244 return ::testing::AssertionSuccess();
245 } else {
246 return ::testing::AssertionFailure()
247 << "Expected " << expected << " but got " << actual
248 << " with a max difference of " << epsilon
249 << " and an actual difference of " << std::abs(expected - actual);
250 }
251 }
252 ::testing::AssertionResult VerifyEstimatorAccurate(double eps) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800253 const Eigen::Matrix<double, 5, 1> true_state = drivetrain_plant_.state();
James Kuszmaul688a2b02020-02-19 18:26:33 -0800254 ::testing::AssertionResult result(true);
255 if (!(result = IsNear(localizer_.x(), true_state(0), eps))) {
256 return result;
257 }
258 if (!(result = IsNear(localizer_.y(), true_state(1), eps))) {
259 return result;
260 }
261 if (!(result = IsNear(localizer_.theta(), true_state(2), eps))) {
262 return result;
263 }
264 if (!(result = IsNear(localizer_.left_velocity(), true_state(3), eps))) {
265 return result;
266 }
267 if (!(result = IsNear(localizer_.right_velocity(), true_state(4), eps))) {
268 return result;
269 }
270 return result;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800271 }
272
273 // Goes through and captures frames on the camera(s), queueing them up to be
274 // sent by SendDelayedFrames().
275 void CaptureFrames() {
276 const frc971::control_loops::Pose robot_pose(
277 {drivetrain_plant_.GetPosition().x(),
278 drivetrain_plant_.GetPosition().y(), 0.0},
279 drivetrain_plant_.state()(2, 0));
280 std::unique_ptr<ImageMatchResultT> frame(new ImageMatchResultT());
281
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800282 for (const auto &H_field_target : TargetLocations()) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800283 std::unique_ptr<CameraPoseT> camera_target(new CameraPoseT());
284
285 camera_target->field_to_target.reset(new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800286 camera_target->field_to_target->data = MatrixToVector(H_field_target);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800287
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800288 Eigen::Matrix<double, 4, 4> H_turret_camera =
James Kuszmaul688a2b02020-02-19 18:26:33 -0800289 Eigen::Matrix<double, 4, 4>::Identity();
290 if (is_turreted_) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800291 H_turret_camera = frc971::control_loops::TransformationMatrixForYaw(
James Kuszmaul688a2b02020-02-19 18:26:33 -0800292 turret_position_) *
293 CameraTurretTransformation();
294 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800295
296 // TODO(james): Use non-zero turret angles.
297 camera_target->camera_to_target.reset(new TransformationMatrixT());
James Kuszmaulaca88782021-04-24 16:48:45 -0700298 camera_target->camera_to_target->data = MatrixToVector(
299 (robot_pose.AsTransformationMatrix() * TurretRobotTransformation() *
300 H_turret_camera * camera_calibration_offset_)
301 .inverse() *
302 H_field_target);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800303
304 frame->camera_poses.emplace_back(std::move(camera_target));
305 }
306
307 frame->image_monotonic_timestamp_ns =
308 chrono::duration_cast<chrono::nanoseconds>(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800309 event_loop_factory()
310 ->GetNodeEventLoopFactory(pi1_)
311 ->monotonic_now()
312 .time_since_epoch())
James Kuszmaul5398fae2020-02-17 16:44:03 -0800313 .count();
314 frame->camera_calibration.reset(new CameraCalibrationT());
315 {
316 frame->camera_calibration->fixed_extrinsics.reset(
317 new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800318 TransformationMatrixT *H_robot_turret =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800319 frame->camera_calibration->fixed_extrinsics.get();
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800320 H_robot_turret->data = MatrixToVector(TurretRobotTransformation());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800321 }
James Kuszmaul688a2b02020-02-19 18:26:33 -0800322
323 if (is_turreted_) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800324 frame->camera_calibration->turret_extrinsics.reset(
325 new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800326 TransformationMatrixT *H_turret_camera =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800327 frame->camera_calibration->turret_extrinsics.get();
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800328 H_turret_camera->data = MatrixToVector(CameraTurretTransformation());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800329 }
330
331 camera_delay_queue_.emplace(monotonic_now(), std::move(frame));
332 }
333
334 // Actually sends out all the camera frames.
335 void SendDelayedFrames() {
336 const std::chrono::milliseconds camera_latency(150);
337 while (!camera_delay_queue_.empty() &&
338 std::get<0>(camera_delay_queue_.front()) <
339 monotonic_now() - camera_latency) {
340 auto builder = camera_sender_.MakeBuilder();
milind1f1dca32021-07-03 13:50:07 -0700341 ASSERT_EQ(
342 builder.Send(ImageMatchResult::Pack(
343 *builder.fbb(), std::get<1>(camera_delay_queue_.front()).get())),
344 aos::RawSender::Error::kOk);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800345 camera_delay_queue_.pop();
346 }
347 }
348
Austin Schuh6aa77be2020-02-22 21:06:40 -0800349 const aos::Node *const roborio_;
350 const aos::Node *const pi1_;
351
James Kuszmaul5398fae2020-02-17 16:44:03 -0800352 std::unique_ptr<aos::EventLoop> drivetrain_event_loop_;
Brian Silverman1f345222020-09-24 21:14:48 -0700353 const frc971::control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800354
Austin Schuh6aa77be2020-02-22 21:06:40 -0800355 std::unique_ptr<aos::EventLoop> pi1_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800356 aos::Sender<ImageMatchResult> camera_sender_;
357
358 Localizer localizer_;
359 DrivetrainLoop drivetrain_;
360
361 std::unique_ptr<aos::EventLoop> drivetrain_plant_event_loop_;
362 DrivetrainSimulation drivetrain_plant_;
363 monotonic_clock::time_point last_frame_;
364
Austin Schuhd027bf52024-05-12 22:24:12 -0700365 std::unique_ptr<aos::EventLoop> test_event_loop_;
366 aos::Sender<Goal> drivetrain_goal_sender_;
367 aos::Fetcher<Goal> drivetrain_goal_fetcher_;
368 aos::Fetcher<frc971::control_loops::drivetrain::Status>
369 drivetrain_status_fetcher_;
370 aos::Sender<LocalizerControl> localizer_control_sender_;
371 aos::Sender<superstructure::Status> superstructure_status_sender_;
372 aos::Sender<aos::message_bridge::ServerStatistics> server_statistics_sender_;
373
James Kuszmaul5398fae2020-02-17 16:44:03 -0800374 // A queue of camera frames so that we can add a time delay to the data
375 // coming from the cameras.
376 std::queue<std::tuple<aos::monotonic_clock::time_point,
377 std::unique_ptr<ImageMatchResultT>>>
378 camera_delay_queue_;
379
James Kuszmaulaca88782021-04-24 16:48:45 -0700380 // Offset to add to the camera for actually taking the images, to simulate an
381 // inaccurate calibration.
382 Eigen::Matrix<double, 4, 4> camera_calibration_offset_ =
383 Eigen::Matrix<double, 4, 4>::Identity();
384
James Kuszmaul5398fae2020-02-17 16:44:03 -0800385 void set_enable_cameras(bool enable) { enable_cameras_ = enable; }
James Kuszmaul688a2b02020-02-19 18:26:33 -0800386 void set_camera_is_turreted(bool turreted) { is_turreted_ = turreted; }
387
388 void set_turret(double position, double velocity) {
389 turret_position_ = position;
390 turret_velocity_ = velocity;
391 }
392
393 void SendGoal(double left, double right) {
394 auto builder = drivetrain_goal_sender_.MakeBuilder();
395
396 Goal::Builder drivetrain_builder = builder.MakeBuilder<Goal>();
397 drivetrain_builder.add_controller_type(
398 frc971::control_loops::drivetrain::ControllerType::MOTION_PROFILE);
399 drivetrain_builder.add_left_goal(left);
400 drivetrain_builder.add_right_goal(right);
401
milind1f1dca32021-07-03 13:50:07 -0700402 EXPECT_EQ(builder.Send(drivetrain_builder.Finish()),
403 aos::RawSender::Error::kOk);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800404 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800405
406 private:
James Kuszmaul688a2b02020-02-19 18:26:33 -0800407 void UpdateTurretPosition() {
408 turret_position_ +=
409 turret_velocity_ *
410 aos::time::DurationInSeconds(monotonic_now() - last_turret_update_);
411 last_turret_update_ = monotonic_now();
412 }
413
James Kuszmaul5398fae2020-02-17 16:44:03 -0800414 bool enable_cameras_ = false;
James Kuszmaul688a2b02020-02-19 18:26:33 -0800415 // Whether to make the camera be on the turret or not.
416 bool is_turreted_ = true;
417
418 // The time at which we last incremented turret_position_.
419 monotonic_clock::time_point last_turret_update_ = monotonic_clock::min_time;
420 // Current turret position and velocity. These are set directly by the user in
421 // the test, and if velocity is non-zero, then we will automatically increment
422 // turret_position_ with every timestep.
423 double turret_position_ = 0.0; // rad
424 double turret_velocity_ = 0.0; // rad / sec
James Kuszmaul5398fae2020-02-17 16:44:03 -0800425
426 std::unique_ptr<aos::EventLoop> logger_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800427 std::unique_ptr<aos::logger::Logger> logger_;
428};
429
430// Tests that no camera updates, combined with a perfect model, results in no
431// error.
432TEST_F(LocalizedDrivetrainTest, NoCameraUpdate) {
433 SetEnabled(true);
434 set_enable_cameras(false);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800435 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800436
James Kuszmaul688a2b02020-02-19 18:26:33 -0800437 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800438
James Kuszmaul0a981402021-10-09 21:00:34 -0700439 RunFor(chrono::seconds(10));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800440 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700441 EXPECT_TRUE(VerifyEstimatorAccurate(5e-3));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800442}
443
James Kuszmaul7f55f072020-03-01 10:21:26 -0800444// Tests that we can drive in a straight line and have things estimate
445// correctly.
446TEST_F(LocalizedDrivetrainTest, NoCameraUpdateStraightLine) {
447 SetEnabled(true);
448 set_enable_cameras(false);
449 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
450
451 SendGoal(1.0, 1.0);
452
James Kuszmaul0a981402021-10-09 21:00:34 -0700453 RunFor(chrono::seconds(3));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800454 VerifyNearGoal();
455 // Due to accelerometer drift, the straight-line driving tends to be less
456 // accurate...
Austin Schuhcadb3292021-01-23 20:24:17 -0800457 EXPECT_TRUE(VerifyEstimatorAccurate(0.15));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800458}
459
James Kuszmaul688a2b02020-02-19 18:26:33 -0800460// Tests that camera updates with a perfect models results in no errors.
James Kuszmaul5398fae2020-02-17 16:44:03 -0800461TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdate) {
462 SetEnabled(true);
463 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800464 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800465
James Kuszmaul688a2b02020-02-19 18:26:33 -0800466 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800467
James Kuszmaul5398fae2020-02-17 16:44:03 -0800468 RunFor(chrono::seconds(3));
469 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700470 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800471}
472
James Kuszmaulaca88782021-04-24 16:48:45 -0700473// Tests that camera updates with a perfect model but incorrect camera pitch
474// results in no errors.
475TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdateWithBadPitch) {
476 // Introduce some camera pitch.
477 camera_calibration_offset_.template block<3, 3>(0, 0) =
478 Eigen::AngleAxis<double>(0.1, Eigen::Vector3d::UnitY())
479 .toRotationMatrix();
480 SetEnabled(true);
481 set_enable_cameras(true);
482 set_camera_is_turreted(true);
483
484 SendGoal(-1.0, 1.0);
485
486 RunFor(chrono::seconds(3));
487 VerifyNearGoal();
James Kuszmaul0a981402021-10-09 21:00:34 -0700488 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaulaca88782021-04-24 16:48:45 -0700489}
490
James Kuszmaul688a2b02020-02-19 18:26:33 -0800491// Tests that camera updates with a constant initial error in the position
James Kuszmaul5398fae2020-02-17 16:44:03 -0800492// results in convergence.
493TEST_F(LocalizedDrivetrainTest, InitialPositionError) {
494 SetEnabled(true);
495 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800496 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800497 drivetrain_plant_.mutable_state()->topRows(3) +=
498 Eigen::Vector3d(0.1, 0.1, 0.01);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800499
James Kuszmaul688a2b02020-02-19 18:26:33 -0800500 // Confirm that some translational movement does get handled correctly.
501 SendGoal(-0.9, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800502
James Kuszmaul5398fae2020-02-17 16:44:03 -0800503 // Give the filters enough time to converge.
504 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700505 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800506 EXPECT_TRUE(VerifyEstimatorAccurate(4e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800507}
508
509// Tests that camera updates using a non-turreted camera work.
510TEST_F(LocalizedDrivetrainTest, InitialPositionErrorNoTurret) {
511 SetEnabled(true);
512 set_enable_cameras(true);
513 set_camera_is_turreted(false);
514 drivetrain_plant_.mutable_state()->topRows(3) +=
515 Eigen::Vector3d(0.1, 0.1, 0.01);
516
517 SendGoal(-1.0, 1.0);
518
519 // Give the filters enough time to converge.
520 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700521 VerifyNearGoal(5e-2);
Austin Schuheb718632021-10-22 22:32:57 -0700522 EXPECT_TRUE(VerifyEstimatorAccurate(0.1));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800523}
524
525// Tests that we are able to handle a constant, non-zero turret angle.
526TEST_F(LocalizedDrivetrainTest, NonZeroTurret) {
527 SetEnabled(true);
528 set_enable_cameras(true);
529 set_camera_is_turreted(true);
530 set_turret(1.0, 0.0);
531 drivetrain_plant_.mutable_state()->topRows(3) +=
532 Eigen::Vector3d(0.1, 0.1, 0.0);
533
534 SendGoal(-1.0, 1.0);
535
536 // Give the filters enough time to converge.
537 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700538 VerifyNearGoal(5e-2);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800539 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800540}
541
542// Tests that we are able to handle a constant velocity turret.
543TEST_F(LocalizedDrivetrainTest, MovingTurret) {
544 SetEnabled(true);
545 set_enable_cameras(true);
546 set_camera_is_turreted(true);
547 set_turret(0.0, 0.2);
548 drivetrain_plant_.mutable_state()->topRows(3) +=
549 Eigen::Vector3d(0.1, 0.1, 0.0);
550
551 SendGoal(-1.0, 1.0);
552
553 // Give the filters enough time to converge.
554 RunFor(chrono::seconds(10));
James Kuszmaul0a981402021-10-09 21:00:34 -0700555 VerifyNearGoal(5e-2);
James Kuszmaul592055e2024-03-23 20:12:59 -0700556 EXPECT_TRUE(VerifyEstimatorAccurate(1e-1));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800557}
558
559// Tests that we reject camera measurements when the turret is spinning too
560// fast.
561TEST_F(LocalizedDrivetrainTest, TooFastTurret) {
562 SetEnabled(true);
563 set_enable_cameras(true);
564 set_camera_is_turreted(true);
565 set_turret(0.0, -10.0);
566 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
567 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
568
569 SendGoal(-1.0, 1.0);
570
571 RunFor(chrono::seconds(10));
572 EXPECT_FALSE(VerifyEstimatorAccurate(1e-3));
573 // If we remove the disturbance, we should now be correct.
574 drivetrain_plant_.mutable_state()->topRows(3) -= disturbance;
James Kuszmaul0a981402021-10-09 21:00:34 -0700575 VerifyNearGoal(5e-2);
576 EXPECT_TRUE(VerifyEstimatorAccurate(2e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800577}
578
579// Tests that we don't reject camera measurements when the turret is spinning
580// too fast but we aren't using a camera attached to the turret.
581TEST_F(LocalizedDrivetrainTest, TooFastTurretDoesntAffectFixedCamera) {
582 SetEnabled(true);
583 set_enable_cameras(true);
584 set_camera_is_turreted(false);
585 set_turret(0.0, -10.0);
586 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
587 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
588
589 SendGoal(-1.0, 1.0);
590
591 RunFor(chrono::seconds(10));
592 VerifyNearGoal(5e-3);
James Kuszmaul592055e2024-03-23 20:12:59 -0700593 EXPECT_TRUE(VerifyEstimatorAccurate(1e-1));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800594}
595
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700596// Tests that we don't blow up if we stop getting updates for an extended period
597// of time and fall behind on fetching fron the cameras.
598TEST_F(LocalizedDrivetrainTest, FetchersHandleTimeGap) {
Austin Schuhd027bf52024-05-12 22:24:12 -0700599 std::unique_ptr<aos::EventLoop> test = MakeEventLoop("test", roborio_);
600
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700601 set_enable_cameras(false);
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700602 set_send_delay(std::chrono::seconds(0));
603 event_loop_factory()->set_network_delay(std::chrono::nanoseconds(1));
Austin Schuhd027bf52024-05-12 22:24:12 -0700604 test->AddTimer([this]() { drivetrain_plant_.set_send_messages(false); })
605 ->Schedule(test->monotonic_now());
606 test->AddPhasedLoop(
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700607 [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));
Austin Schuhd027bf52024-05-12 22:24:12 -0700614 test->AddTimer([this]() {
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700615 drivetrain_plant_.set_send_messages(true);
616 SimulateSensorReset();
617 })
Austin Schuhd027bf52024-05-12 22:24:12 -0700618 ->Schedule(test->monotonic_now() + std::chrono::seconds(10));
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700619
620 RunFor(chrono::seconds(20));
621}
622
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800623} // namespace y2020::control_loops::drivetrain::testing