blob: 951a2866f6138e1bbfb4915b6cf22f9ade2ea519 [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 Schuh99f7c6a2024-06-25 22:07:44 -07005#include "absl/flags/flag.h"
Philipp Schrader790cb542023-07-05 21:06:52 -07006#include "gtest/gtest.h"
7
Austin Schuhb06f03b2021-02-17 22:00:37 -08008#include "aos/events/logging/log_writer.h"
James Kuszmaul958b21e2020-02-26 21:51:40 -08009#include "aos/network/message_bridge_server_generated.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -080010#include "aos/network/team_number.h"
James Kuszmaul61750662021-06-21 21:32:33 -070011#include "frc971/control_loops/control_loop_test.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -080012#include "frc971/control_loops/drivetrain/drivetrain.h"
13#include "frc971/control_loops/drivetrain/drivetrain_test_lib.h"
14#include "frc971/control_loops/team_number_test_environment.h"
15#include "y2020/control_loops/drivetrain/drivetrain_base.h"
James Kuszmaul688a2b02020-02-19 18:26:33 -080016#include "y2020/control_loops/superstructure/superstructure_status_generated.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -080017
Austin Schuh99f7c6a2024-06-25 22:07:44 -070018ABSL_FLAG(std::string, output_file, "",
19 "If set, logs all channels to the provided logfile.");
James Kuszmaul5398fae2020-02-17 16:44:03 -080020
21// This file tests that the full 2020 localizer behaves sanely.
22
Stephan Pleinesf63bde82024-01-13 15:59:33 -080023namespace y2020::control_loops::drivetrain::testing {
James Kuszmaul5398fae2020-02-17 16:44:03 -080024
Austin Schuh66168842021-08-17 19:42:21 -070025using aos::logger::BootTimestamp;
James Kuszmaul5398fae2020-02-17 16:44:03 -080026using frc971::control_loops::drivetrain::DrivetrainConfig;
27using frc971::control_loops::drivetrain::Goal;
28using frc971::control_loops::drivetrain::LocalizerControl;
Brian Silverman1f345222020-09-24 21:14:48 -070029using frc971::vision::sift::CameraCalibrationT;
30using frc971::vision::sift::CameraPoseT;
James Kuszmaul5398fae2020-02-17 16:44:03 -080031using frc971::vision::sift::ImageMatchResult;
32using frc971::vision::sift::ImageMatchResultT;
James Kuszmaul5398fae2020-02-17 16:44:03 -080033using frc971::vision::sift::TransformationMatrixT;
34
35namespace {
36DrivetrainConfig<double> GetTest2020DrivetrainConfig() {
37 DrivetrainConfig<double> config = GetDrivetrainConfig();
38 return config;
39}
40
41// Copies an Eigen matrix into a row-major vector of the data.
42std::vector<float> MatrixToVector(const Eigen::Matrix<double, 4, 4> &H) {
43 std::vector<float> data;
44 for (int row = 0; row < 4; ++row) {
45 for (int col = 0; col < 4; ++col) {
46 data.push_back(H(row, col));
47 }
48 }
49 return data;
50}
51
52// Provides the location of the turret to use for simulation. Mostly we care
53// about providing a location that is not perfectly aligned with the robot's
54// origin.
55Eigen::Matrix<double, 4, 4> TurretRobotTransformation() {
56 Eigen::Matrix<double, 4, 4> H;
57 H.setIdentity();
James Kuszmaul688a2b02020-02-19 18:26:33 -080058 H.block<3, 1>(0, 3) << 1, 1.1, 0.9;
James Kuszmaul5398fae2020-02-17 16:44:03 -080059 return H;
60}
61
62// Provides the location of the camera on the turret.
63// TODO(james): Also simulate a fixed camera that is *not* on the turret.
64Eigen::Matrix<double, 4, 4> CameraTurretTransformation() {
65 Eigen::Matrix<double, 4, 4> H;
66 H.setIdentity();
67 H.block<3, 1>(0, 3) << 0.1, 0, 0;
68 // Introduce a bit of pitch to make sure that we're exercising all the code.
69 H.block<3, 3>(0, 0) =
James Kuszmaul688a2b02020-02-19 18:26:33 -080070 Eigen::AngleAxis<double>(0.1, Eigen::Vector3d::UnitY()) *
James Kuszmaul5398fae2020-02-17 16:44:03 -080071 H.block<3, 3>(0, 0);
72 return H;
73}
74
75// The absolute target location to use. Not meant to correspond with a
76// particular field target.
77// TODO(james): Make more targets.
James Kuszmaul688a2b02020-02-19 18:26:33 -080078std::vector<Eigen::Matrix<double, 4, 4>> TargetLocations() {
79 std::vector<Eigen::Matrix<double, 4, 4>> locations;
James Kuszmaul5398fae2020-02-17 16:44:03 -080080 Eigen::Matrix<double, 4, 4> H;
81 H.setIdentity();
82 H.block<3, 1>(0, 3) << 10.0, 0, 0;
James Kuszmaul688a2b02020-02-19 18:26:33 -080083 locations.push_back(H);
84 H.block<3, 1>(0, 3) << -10.0, 0, 0;
James Kuszmaul5a46c8d2021-09-03 19:33:48 -070085 H.block<3, 3>(0, 0) =
86 Eigen::AngleAxis<double>(1.1, Eigen::Vector3d::UnitZ()) *
87 H.block<3, 3>(0, 0);
James Kuszmaul688a2b02020-02-19 18:26:33 -080088 locations.push_back(H);
89 return locations;
James Kuszmaul5398fae2020-02-17 16:44:03 -080090}
James Kuszmaul958b21e2020-02-26 21:51:40 -080091
James Kuszmaul8866e642022-06-10 16:00:36 -070092constexpr std::chrono::seconds kPiTimeOffset(10);
James Kuszmaul5398fae2020-02-17 16:44:03 -080093} // namespace
94
95namespace chrono = std::chrono;
James Kuszmaul5398fae2020-02-17 16:44:03 -080096using aos::monotonic_clock;
Brian Silverman1f345222020-09-24 21:14:48 -070097using frc971::control_loops::drivetrain::DrivetrainLoop;
98using frc971::control_loops::drivetrain::testing::DrivetrainSimulation;
James Kuszmaul5398fae2020-02-17 16:44:03 -080099
James Kuszmaul61750662021-06-21 21:32:33 -0700100class LocalizedDrivetrainTest : public frc971::testing::ControlLoopTest {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800101 protected:
102 // We must use the 2020 drivetrain config so that we don't have to deal
103 // with shifting:
104 LocalizedDrivetrainTest()
James Kuszmaul61750662021-06-21 21:32:33 -0700105 : frc971::testing::ControlLoopTest(
James Kuszmaul5398fae2020-02-17 16:44:03 -0800106 aos::configuration::ReadConfig(
107 "y2020/control_loops/drivetrain/simulation_config.json"),
Austin Schuh0debde12022-08-17 16:25:17 -0700108 GetTest2020DrivetrainConfig().dt,
109 {{BootTimestamp::epoch() + kPiTimeOffset,
110 BootTimestamp::epoch() + kPiTimeOffset,
111 BootTimestamp::epoch() + kPiTimeOffset,
112 BootTimestamp::epoch() + kPiTimeOffset,
113 BootTimestamp::epoch() + kPiTimeOffset,
114 BootTimestamp::epoch() + kPiTimeOffset, BootTimestamp::epoch()}}),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800115 roborio_(aos::configuration::GetNode(configuration(), "roborio")),
116 pi1_(aos::configuration::GetNode(configuration(), "pi1")),
Austin Schuhd027bf52024-05-12 22:24:12 -0700117 drivetrain_event_loop_(MakeEventLoop("drivetrain", roborio_)),
118 dt_config_(GetTest2020DrivetrainConfig()),
119 pi1_event_loop_(MakeEventLoop("test", pi1_)),
120 camera_sender_(
121 pi1_event_loop_->MakeSender<ImageMatchResult>("/pi1/camera")),
122 localizer_(drivetrain_event_loop_.get(), dt_config_),
123 drivetrain_(dt_config_, drivetrain_event_loop_.get(), &localizer_),
124 drivetrain_plant_event_loop_(MakeEventLoop("plant", roborio_)),
125 drivetrain_plant_(drivetrain_plant_event_loop_.get(), dt_config_),
126 last_frame_(monotonic_now()),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800127 test_event_loop_(MakeEventLoop("test", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800128 drivetrain_goal_sender_(
129 test_event_loop_->MakeSender<Goal>("/drivetrain")),
130 drivetrain_goal_fetcher_(
131 test_event_loop_->MakeFetcher<Goal>("/drivetrain")),
James Kuszmaul0a981402021-10-09 21:00:34 -0700132 drivetrain_status_fetcher_(
133 test_event_loop_
134 ->MakeFetcher<frc971::control_loops::drivetrain::Status>(
135 "/drivetrain")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800136 localizer_control_sender_(
137 test_event_loop_->MakeSender<LocalizerControl>("/drivetrain")),
James Kuszmaul688a2b02020-02-19 18:26:33 -0800138 superstructure_status_sender_(
139 test_event_loop_->MakeSender<superstructure::Status>(
140 "/superstructure")),
James Kuszmaul958b21e2020-02-26 21:51:40 -0800141 server_statistics_sender_(
142 test_event_loop_->MakeSender<aos::message_bridge::ServerStatistics>(
Austin Schuhd027bf52024-05-12 22:24:12 -0700143 "/aos")) {
James Kuszmaul9c128122021-03-22 22:24:36 -0700144 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), roborio_), 6);
Austin Schuh87dd3832021-01-01 23:07:31 -0800145 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), pi1_), 1);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800146 set_team_id(frc971::control_loops::testing::kTeamNumber);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800147 set_battery_voltage(12.0);
148
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700149 if (!absl::GetFlag(FLAGS_output_file).empty()) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800150 logger_event_loop_ = MakeEventLoop("logger", roborio_);
Brian Silverman1f345222020-09-24 21:14:48 -0700151 logger_ = std::make_unique<aos::logger::Logger>(logger_event_loop_.get());
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700152 logger_->StartLoggingOnRun(absl::GetFlag(FLAGS_output_file));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800153 }
154
155 test_event_loop_->MakeWatcher(
156 "/drivetrain",
157 [this](const frc971::control_loops::drivetrain::Status &) {
158 // Needs to do camera updates right after we run the control loop.
159 if (enable_cameras_) {
160 SendDelayedFrames();
161 if (last_frame_ + std::chrono::milliseconds(100) <
162 monotonic_now()) {
163 CaptureFrames();
164 last_frame_ = monotonic_now();
165 }
166 }
Brian Silverman1f345222020-09-24 21:14:48 -0700167 });
James Kuszmaul688a2b02020-02-19 18:26:33 -0800168
169 test_event_loop_->AddPhasedLoop(
170 [this](int) {
James Kuszmaul0a981402021-10-09 21:00:34 -0700171 // TODO(james): This is wrong. At a bare minimum, it is missing a boot
172 // UUID, and this is probably the wrong pattern entirely.
James Kuszmaul958b21e2020-02-26 21:51:40 -0800173 auto builder = server_statistics_sender_.MakeBuilder();
174 auto name_offset = builder.fbb()->CreateString("pi1");
175 auto node_builder = builder.MakeBuilder<aos::Node>();
176 node_builder.add_name(name_offset);
177 auto node_offset = node_builder.Finish();
178 auto connection_builder =
179 builder.MakeBuilder<aos::message_bridge::ServerConnection>();
180 connection_builder.add_node(node_offset);
181 connection_builder.add_monotonic_offset(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700182 chrono::duration_cast<chrono::nanoseconds>(kPiTimeOffset)
James Kuszmaul958b21e2020-02-26 21:51:40 -0800183 .count());
184 auto connection_offset = connection_builder.Finish();
185 auto connections_offset =
186 builder.fbb()->CreateVector(&connection_offset, 1);
187 auto statistics_builder =
188 builder.MakeBuilder<aos::message_bridge::ServerStatistics>();
189 statistics_builder.add_connections(connections_offset);
milind1f1dca32021-07-03 13:50:07 -0700190 CHECK_EQ(builder.Send(statistics_builder.Finish()),
191 aos::RawSender::Error::kOk);
James Kuszmaul958b21e2020-02-26 21:51:40 -0800192 },
193 chrono::milliseconds(500));
194
195 test_event_loop_->AddPhasedLoop(
196 [this](int) {
James Kuszmaul688a2b02020-02-19 18:26:33 -0800197 // Also use the opportunity to send out turret messages.
198 UpdateTurretPosition();
199 auto builder = superstructure_status_sender_.MakeBuilder();
200 auto turret_builder =
201 builder
202 .MakeBuilder<frc971::control_loops::
203 PotAndAbsoluteEncoderProfiledJointStatus>();
204 turret_builder.add_position(turret_position_);
205 turret_builder.add_velocity(turret_velocity_);
206 auto turret_offset = turret_builder.Finish();
207 auto status_builder = builder.MakeBuilder<superstructure::Status>();
208 status_builder.add_turret(turret_offset);
milind1f1dca32021-07-03 13:50:07 -0700209 CHECK_EQ(builder.Send(status_builder.Finish()),
210 aos::RawSender::Error::kOk);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800211 },
Yash Chainania6fe97b2021-12-15 21:01:11 -0800212 frc971::controls::kLoopFrequency);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800213
James Kuszmaul286b4282020-02-26 20:29:32 -0800214 test_event_loop_->OnRun([this]() { SetStartingPosition({3.0, 2.0, 0.0}); });
215
James Kuszmaul5398fae2020-02-17 16:44:03 -0800216 // Run for enough time to allow the gyro/imu zeroing code to run.
James Kuszmaul0a981402021-10-09 21:00:34 -0700217 RunFor(std::chrono::seconds(15));
218 CHECK(drivetrain_status_fetcher_.Fetch());
Austin Schuh6bdcc372024-06-27 14:49:11 -0700219 CHECK(drivetrain_status_fetcher_->zeroing() != nullptr);
220 EXPECT_TRUE(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> drivetrain_event_loop_;
Brian Silverman1f345222020-09-24 21:14:48 -0700354 const frc971::control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800355
Austin Schuh6aa77be2020-02-22 21:06:40 -0800356 std::unique_ptr<aos::EventLoop> pi1_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800357 aos::Sender<ImageMatchResult> camera_sender_;
358
359 Localizer localizer_;
360 DrivetrainLoop drivetrain_;
361
362 std::unique_ptr<aos::EventLoop> drivetrain_plant_event_loop_;
363 DrivetrainSimulation drivetrain_plant_;
364 monotonic_clock::time_point last_frame_;
365
Austin Schuhd027bf52024-05-12 22:24:12 -0700366 std::unique_ptr<aos::EventLoop> test_event_loop_;
367 aos::Sender<Goal> drivetrain_goal_sender_;
368 aos::Fetcher<Goal> drivetrain_goal_fetcher_;
369 aos::Fetcher<frc971::control_loops::drivetrain::Status>
370 drivetrain_status_fetcher_;
371 aos::Sender<LocalizerControl> localizer_control_sender_;
372 aos::Sender<superstructure::Status> superstructure_status_sender_;
373 aos::Sender<aos::message_bridge::ServerStatistics> server_statistics_sender_;
374
James Kuszmaul5398fae2020-02-17 16:44:03 -0800375 // 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 Kuszmaul592055e2024-03-23 20:12:59 -0700557 EXPECT_TRUE(VerifyEstimatorAccurate(1e-1));
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);
James Kuszmaul592055e2024-03-23 20:12:59 -0700594 EXPECT_TRUE(VerifyEstimatorAccurate(1e-1));
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) {
Austin Schuhd027bf52024-05-12 22:24:12 -0700600 std::unique_ptr<aos::EventLoop> test = MakeEventLoop("test", roborio_);
601
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700602 set_enable_cameras(false);
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700603 set_send_delay(std::chrono::seconds(0));
604 event_loop_factory()->set_network_delay(std::chrono::nanoseconds(1));
Austin Schuhd027bf52024-05-12 22:24:12 -0700605 test->AddTimer([this]() { drivetrain_plant_.set_send_messages(false); })
606 ->Schedule(test->monotonic_now());
607 test->AddPhasedLoop(
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700608 [this](int) {
609 auto builder = camera_sender_.MakeBuilder();
610 ImageMatchResultT image;
milind1f1dca32021-07-03 13:50:07 -0700611 ASSERT_EQ(builder.Send(ImageMatchResult::Pack(*builder.fbb(), &image)),
612 aos::RawSender::Error::kOk);
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700613 },
milind945708b2021-07-03 13:30:15 -0700614 std::chrono::milliseconds(40));
Austin Schuhd027bf52024-05-12 22:24:12 -0700615 test->AddTimer([this]() {
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700616 drivetrain_plant_.set_send_messages(true);
617 SimulateSensorReset();
618 })
Austin Schuhd027bf52024-05-12 22:24:12 -0700619 ->Schedule(test->monotonic_now() + std::chrono::seconds(10));
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700620
621 RunFor(chrono::seconds(20));
622}
623
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800624} // namespace y2020::control_loops::drivetrain::testing