blob: d195b5dca09e215af3dc3d442314c966a9303938 [file] [log] [blame]
James Kuszmaul5398fae2020-02-17 16:44:03 -08001#include <queue>
2
3#include "gtest/gtest.h"
4
5#include "aos/controls/control_loop_test.h"
Austin Schuhb06f03b2021-02-17 22:00:37 -08006#include "aos/events/logging/log_writer.h"
James Kuszmaul958b21e2020-02-26 21:51:40 -08007#include "aos/network/message_bridge_server_generated.h"
James Kuszmaul5398fae2020-02-17 16:44:03 -08008#include "aos/network/team_number.h"
Austin Schuh87dd3832021-01-01 23:07:31 -08009#include "aos/network/testing_time_converter.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"
13#include "y2020/control_loops/drivetrain/drivetrain_base.h"
14#include "y2020/control_loops/drivetrain/localizer.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
27using frc971::control_loops::drivetrain::DrivetrainConfig;
28using frc971::control_loops::drivetrain::Goal;
29using frc971::control_loops::drivetrain::LocalizerControl;
Brian Silverman1f345222020-09-24 21:14:48 -070030using frc971::vision::sift::CameraCalibrationT;
31using frc971::vision::sift::CameraPoseT;
James Kuszmaul5398fae2020-02-17 16:44:03 -080032using frc971::vision::sift::ImageMatchResult;
33using frc971::vision::sift::ImageMatchResultT;
James Kuszmaul5398fae2020-02-17 16:44:03 -080034using frc971::vision::sift::TransformationMatrixT;
35
36namespace {
37DrivetrainConfig<double> GetTest2020DrivetrainConfig() {
38 DrivetrainConfig<double> config = GetDrivetrainConfig();
39 return config;
40}
41
42// Copies an Eigen matrix into a row-major vector of the data.
43std::vector<float> MatrixToVector(const Eigen::Matrix<double, 4, 4> &H) {
44 std::vector<float> data;
45 for (int row = 0; row < 4; ++row) {
46 for (int col = 0; col < 4; ++col) {
47 data.push_back(H(row, col));
48 }
49 }
50 return data;
51}
52
53// Provides the location of the turret to use for simulation. Mostly we care
54// about providing a location that is not perfectly aligned with the robot's
55// origin.
56Eigen::Matrix<double, 4, 4> TurretRobotTransformation() {
57 Eigen::Matrix<double, 4, 4> H;
58 H.setIdentity();
James Kuszmaul688a2b02020-02-19 18:26:33 -080059 H.block<3, 1>(0, 3) << 1, 1.1, 0.9;
James Kuszmaul5398fae2020-02-17 16:44:03 -080060 return H;
61}
62
63// Provides the location of the camera on the turret.
64// TODO(james): Also simulate a fixed camera that is *not* on the turret.
65Eigen::Matrix<double, 4, 4> CameraTurretTransformation() {
66 Eigen::Matrix<double, 4, 4> H;
67 H.setIdentity();
68 H.block<3, 1>(0, 3) << 0.1, 0, 0;
69 // Introduce a bit of pitch to make sure that we're exercising all the code.
70 H.block<3, 3>(0, 0) =
James Kuszmaul688a2b02020-02-19 18:26:33 -080071 Eigen::AngleAxis<double>(0.1, Eigen::Vector3d::UnitY()) *
James Kuszmaul5398fae2020-02-17 16:44:03 -080072 H.block<3, 3>(0, 0);
73 return H;
74}
75
76// The absolute target location to use. Not meant to correspond with a
77// particular field target.
78// TODO(james): Make more targets.
James Kuszmaul688a2b02020-02-19 18:26:33 -080079std::vector<Eigen::Matrix<double, 4, 4>> TargetLocations() {
80 std::vector<Eigen::Matrix<double, 4, 4>> locations;
James Kuszmaul5398fae2020-02-17 16:44:03 -080081 Eigen::Matrix<double, 4, 4> H;
82 H.setIdentity();
83 H.block<3, 1>(0, 3) << 10.0, 0, 0;
James Kuszmaul688a2b02020-02-19 18:26:33 -080084 locations.push_back(H);
85 H.block<3, 1>(0, 3) << -10.0, 0, 0;
86 locations.push_back(H);
87 return locations;
James Kuszmaul5398fae2020-02-17 16:44:03 -080088}
James Kuszmaul958b21e2020-02-26 21:51:40 -080089
Austin Schuhbe69cf32020-08-27 11:38:33 -070090constexpr std::chrono::seconds kPiTimeOffset(-10);
James Kuszmaul5398fae2020-02-17 16:44:03 -080091} // namespace
92
93namespace chrono = std::chrono;
James Kuszmaul5398fae2020-02-17 16:44:03 -080094using aos::monotonic_clock;
Brian Silverman1f345222020-09-24 21:14:48 -070095using frc971::control_loops::drivetrain::DrivetrainLoop;
96using frc971::control_loops::drivetrain::testing::DrivetrainSimulation;
James Kuszmaul5398fae2020-02-17 16:44:03 -080097
James Kuszmaul688a2b02020-02-19 18:26:33 -080098class LocalizedDrivetrainTest : public aos::testing::ControlLoopTest {
James Kuszmaul5398fae2020-02-17 16:44:03 -080099 protected:
100 // We must use the 2020 drivetrain config so that we don't have to deal
101 // with shifting:
102 LocalizedDrivetrainTest()
103 : aos::testing::ControlLoopTest(
104 aos::configuration::ReadConfig(
105 "y2020/control_loops/drivetrain/simulation_config.json"),
106 GetTest2020DrivetrainConfig().dt),
Austin Schuh87dd3832021-01-01 23:07:31 -0800107 time_converter_(aos::configuration::NodesCount(configuration())),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800108 roborio_(aos::configuration::GetNode(configuration(), "roborio")),
109 pi1_(aos::configuration::GetNode(configuration(), "pi1")),
110 test_event_loop_(MakeEventLoop("test", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800111 drivetrain_goal_sender_(
112 test_event_loop_->MakeSender<Goal>("/drivetrain")),
113 drivetrain_goal_fetcher_(
114 test_event_loop_->MakeFetcher<Goal>("/drivetrain")),
115 localizer_control_sender_(
116 test_event_loop_->MakeSender<LocalizerControl>("/drivetrain")),
James Kuszmaul688a2b02020-02-19 18:26:33 -0800117 superstructure_status_sender_(
118 test_event_loop_->MakeSender<superstructure::Status>(
119 "/superstructure")),
James Kuszmaul958b21e2020-02-26 21:51:40 -0800120 server_statistics_sender_(
121 test_event_loop_->MakeSender<aos::message_bridge::ServerStatistics>(
122 "/aos")),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800123 drivetrain_event_loop_(MakeEventLoop("drivetrain", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800124 dt_config_(GetTest2020DrivetrainConfig()),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800125 pi1_event_loop_(MakeEventLoop("test", pi1_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800126 camera_sender_(
Austin Schuh6aa77be2020-02-22 21:06:40 -0800127 pi1_event_loop_->MakeSender<ImageMatchResult>("/pi1/camera")),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800128 localizer_(drivetrain_event_loop_.get(), dt_config_),
129 drivetrain_(dt_config_, drivetrain_event_loop_.get(), &localizer_),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800130 drivetrain_plant_event_loop_(MakeEventLoop("plant", roborio_)),
James Kuszmaul5398fae2020-02-17 16:44:03 -0800131 drivetrain_plant_(drivetrain_plant_event_loop_.get(), dt_config_),
132 last_frame_(monotonic_now()) {
Austin Schuh87dd3832021-01-01 23:07:31 -0800133 event_loop_factory()->SetTimeConverter(&time_converter_);
134 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), roborio_), 5);
135 CHECK_EQ(aos::configuration::GetNodeIndex(configuration(), pi1_), 1);
136 time_converter_.AddMonotonic({monotonic_clock::epoch() + kPiTimeOffset,
137 monotonic_clock::epoch() + kPiTimeOffset,
138 monotonic_clock::epoch() + kPiTimeOffset,
139 monotonic_clock::epoch() + kPiTimeOffset,
140 monotonic_clock::epoch() + kPiTimeOffset,
141 monotonic_clock::epoch()});
James Kuszmaul5398fae2020-02-17 16:44:03 -0800142 set_team_id(frc971::control_loops::testing::kTeamNumber);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800143 set_battery_voltage(12.0);
144
145 if (!FLAGS_output_file.empty()) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800146 logger_event_loop_ = MakeEventLoop("logger", roborio_);
Brian Silverman1f345222020-09-24 21:14:48 -0700147 logger_ = std::make_unique<aos::logger::Logger>(logger_event_loop_.get());
148 logger_->StartLoggingLocalNamerOnRun(FLAGS_output_file);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800149 }
150
151 test_event_loop_->MakeWatcher(
152 "/drivetrain",
153 [this](const frc971::control_loops::drivetrain::Status &) {
154 // Needs to do camera updates right after we run the control loop.
155 if (enable_cameras_) {
156 SendDelayedFrames();
157 if (last_frame_ + std::chrono::milliseconds(100) <
158 monotonic_now()) {
159 CaptureFrames();
160 last_frame_ = monotonic_now();
161 }
162 }
Brian Silverman1f345222020-09-24 21:14:48 -0700163 });
James Kuszmaul688a2b02020-02-19 18:26:33 -0800164
165 test_event_loop_->AddPhasedLoop(
166 [this](int) {
James Kuszmaul958b21e2020-02-26 21:51:40 -0800167 auto builder = server_statistics_sender_.MakeBuilder();
168 auto name_offset = builder.fbb()->CreateString("pi1");
169 auto node_builder = builder.MakeBuilder<aos::Node>();
170 node_builder.add_name(name_offset);
171 auto node_offset = node_builder.Finish();
172 auto connection_builder =
173 builder.MakeBuilder<aos::message_bridge::ServerConnection>();
174 connection_builder.add_node(node_offset);
175 connection_builder.add_monotonic_offset(
Austin Schuhbe69cf32020-08-27 11:38:33 -0700176 chrono::duration_cast<chrono::nanoseconds>(kPiTimeOffset)
James Kuszmaul958b21e2020-02-26 21:51:40 -0800177 .count());
178 auto connection_offset = connection_builder.Finish();
179 auto connections_offset =
180 builder.fbb()->CreateVector(&connection_offset, 1);
181 auto statistics_builder =
182 builder.MakeBuilder<aos::message_bridge::ServerStatistics>();
183 statistics_builder.add_connections(connections_offset);
184 builder.Send(statistics_builder.Finish());
185 },
186 chrono::milliseconds(500));
187
188 test_event_loop_->AddPhasedLoop(
189 [this](int) {
James Kuszmaul688a2b02020-02-19 18:26:33 -0800190 // Also use the opportunity to send out turret messages.
191 UpdateTurretPosition();
192 auto builder = superstructure_status_sender_.MakeBuilder();
193 auto turret_builder =
194 builder
195 .MakeBuilder<frc971::control_loops::
196 PotAndAbsoluteEncoderProfiledJointStatus>();
197 turret_builder.add_position(turret_position_);
198 turret_builder.add_velocity(turret_velocity_);
199 auto turret_offset = turret_builder.Finish();
200 auto status_builder = builder.MakeBuilder<superstructure::Status>();
201 status_builder.add_turret(turret_offset);
202 builder.Send(status_builder.Finish());
203 },
204 chrono::milliseconds(5));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800205
James Kuszmaul286b4282020-02-26 20:29:32 -0800206 test_event_loop_->OnRun([this]() { SetStartingPosition({3.0, 2.0, 0.0}); });
207
James Kuszmaul5398fae2020-02-17 16:44:03 -0800208 // Run for enough time to allow the gyro/imu zeroing code to run.
209 RunFor(std::chrono::seconds(10));
210 }
211
212 virtual ~LocalizedDrivetrainTest() override {}
213
214 void SetStartingPosition(const Eigen::Matrix<double, 3, 1> &xytheta) {
215 *drivetrain_plant_.mutable_state() << xytheta.x(), xytheta.y(),
216 xytheta(2, 0), 0.0, 0.0;
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700217 Eigen::Matrix<double, Localizer::HybridEkf::kNStates, 1> localizer_state;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800218 localizer_state.setZero();
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700219 localizer_state.block<3, 1>(0, 0) = xytheta;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800220 localizer_.Reset(monotonic_now(), localizer_state);
221 }
222
223 void VerifyNearGoal(double eps = 1e-3) {
224 drivetrain_goal_fetcher_.Fetch();
225 EXPECT_NEAR(drivetrain_goal_fetcher_->left_goal(),
226 drivetrain_plant_.GetLeftPosition(), eps);
227 EXPECT_NEAR(drivetrain_goal_fetcher_->right_goal(),
228 drivetrain_plant_.GetRightPosition(), eps);
229 }
230
James Kuszmaul688a2b02020-02-19 18:26:33 -0800231 ::testing::AssertionResult IsNear(double expected, double actual,
232 double epsilon) {
233 if (std::abs(expected - actual) < epsilon) {
234 return ::testing::AssertionSuccess();
235 } else {
236 return ::testing::AssertionFailure()
237 << "Expected " << expected << " but got " << actual
238 << " with a max difference of " << epsilon
239 << " and an actual difference of " << std::abs(expected - actual);
240 }
241 }
242 ::testing::AssertionResult VerifyEstimatorAccurate(double eps) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800243 const Eigen::Matrix<double, 5, 1> true_state = drivetrain_plant_.state();
James Kuszmaul688a2b02020-02-19 18:26:33 -0800244 ::testing::AssertionResult result(true);
245 if (!(result = IsNear(localizer_.x(), true_state(0), eps))) {
246 return result;
247 }
248 if (!(result = IsNear(localizer_.y(), true_state(1), eps))) {
249 return result;
250 }
251 if (!(result = IsNear(localizer_.theta(), true_state(2), eps))) {
252 return result;
253 }
254 if (!(result = IsNear(localizer_.left_velocity(), true_state(3), eps))) {
255 return result;
256 }
257 if (!(result = IsNear(localizer_.right_velocity(), true_state(4), eps))) {
258 return result;
259 }
260 return result;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800261 }
262
263 // Goes through and captures frames on the camera(s), queueing them up to be
264 // sent by SendDelayedFrames().
265 void CaptureFrames() {
266 const frc971::control_loops::Pose robot_pose(
267 {drivetrain_plant_.GetPosition().x(),
268 drivetrain_plant_.GetPosition().y(), 0.0},
269 drivetrain_plant_.state()(2, 0));
270 std::unique_ptr<ImageMatchResultT> frame(new ImageMatchResultT());
271
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800272 for (const auto &H_field_target : TargetLocations()) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800273 std::unique_ptr<CameraPoseT> camera_target(new CameraPoseT());
274
275 camera_target->field_to_target.reset(new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800276 camera_target->field_to_target->data = MatrixToVector(H_field_target);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800277
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800278 Eigen::Matrix<double, 4, 4> H_turret_camera =
James Kuszmaul688a2b02020-02-19 18:26:33 -0800279 Eigen::Matrix<double, 4, 4>::Identity();
280 if (is_turreted_) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800281 H_turret_camera = frc971::control_loops::TransformationMatrixForYaw(
James Kuszmaul688a2b02020-02-19 18:26:33 -0800282 turret_position_) *
283 CameraTurretTransformation();
284 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800285
286 // TODO(james): Use non-zero turret angles.
287 camera_target->camera_to_target.reset(new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800288 camera_target->camera_to_target->data =
289 MatrixToVector((robot_pose.AsTransformationMatrix() *
290 TurretRobotTransformation() * H_turret_camera)
291 .inverse() *
292 H_field_target);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800293
294 frame->camera_poses.emplace_back(std::move(camera_target));
295 }
296
297 frame->image_monotonic_timestamp_ns =
298 chrono::duration_cast<chrono::nanoseconds>(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800299 event_loop_factory()
300 ->GetNodeEventLoopFactory(pi1_)
301 ->monotonic_now()
302 .time_since_epoch())
James Kuszmaul5398fae2020-02-17 16:44:03 -0800303 .count();
304 frame->camera_calibration.reset(new CameraCalibrationT());
305 {
306 frame->camera_calibration->fixed_extrinsics.reset(
307 new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800308 TransformationMatrixT *H_robot_turret =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800309 frame->camera_calibration->fixed_extrinsics.get();
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800310 H_robot_turret->data = MatrixToVector(TurretRobotTransformation());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800311 }
James Kuszmaul688a2b02020-02-19 18:26:33 -0800312
313 if (is_turreted_) {
James Kuszmaul5398fae2020-02-17 16:44:03 -0800314 frame->camera_calibration->turret_extrinsics.reset(
315 new TransformationMatrixT());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800316 TransformationMatrixT *H_turret_camera =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800317 frame->camera_calibration->turret_extrinsics.get();
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800318 H_turret_camera->data = MatrixToVector(CameraTurretTransformation());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800319 }
320
321 camera_delay_queue_.emplace(monotonic_now(), std::move(frame));
322 }
323
324 // Actually sends out all the camera frames.
325 void SendDelayedFrames() {
326 const std::chrono::milliseconds camera_latency(150);
327 while (!camera_delay_queue_.empty() &&
328 std::get<0>(camera_delay_queue_.front()) <
329 monotonic_now() - camera_latency) {
330 auto builder = camera_sender_.MakeBuilder();
331 ASSERT_TRUE(builder.Send(ImageMatchResult::Pack(
332 *builder.fbb(), std::get<1>(camera_delay_queue_.front()).get())));
333 camera_delay_queue_.pop();
334 }
335 }
336
Austin Schuh87dd3832021-01-01 23:07:31 -0800337 aos::message_bridge::TestingTimeConverter time_converter_;
338
Austin Schuh6aa77be2020-02-22 21:06:40 -0800339 const aos::Node *const roborio_;
340 const aos::Node *const pi1_;
341
James Kuszmaul5398fae2020-02-17 16:44:03 -0800342 std::unique_ptr<aos::EventLoop> test_event_loop_;
343 aos::Sender<Goal> drivetrain_goal_sender_;
344 aos::Fetcher<Goal> drivetrain_goal_fetcher_;
345 aos::Sender<LocalizerControl> localizer_control_sender_;
James Kuszmaul688a2b02020-02-19 18:26:33 -0800346 aos::Sender<superstructure::Status> superstructure_status_sender_;
James Kuszmaul958b21e2020-02-26 21:51:40 -0800347 aos::Sender<aos::message_bridge::ServerStatistics> server_statistics_sender_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800348
349 std::unique_ptr<aos::EventLoop> drivetrain_event_loop_;
Brian Silverman1f345222020-09-24 21:14:48 -0700350 const frc971::control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800351
Austin Schuh6aa77be2020-02-22 21:06:40 -0800352 std::unique_ptr<aos::EventLoop> pi1_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800353 aos::Sender<ImageMatchResult> camera_sender_;
354
355 Localizer localizer_;
356 DrivetrainLoop drivetrain_;
357
358 std::unique_ptr<aos::EventLoop> drivetrain_plant_event_loop_;
359 DrivetrainSimulation drivetrain_plant_;
360 monotonic_clock::time_point last_frame_;
361
362 // A queue of camera frames so that we can add a time delay to the data
363 // coming from the cameras.
364 std::queue<std::tuple<aos::monotonic_clock::time_point,
365 std::unique_ptr<ImageMatchResultT>>>
366 camera_delay_queue_;
367
368 void set_enable_cameras(bool enable) { enable_cameras_ = enable; }
James Kuszmaul688a2b02020-02-19 18:26:33 -0800369 void set_camera_is_turreted(bool turreted) { is_turreted_ = turreted; }
370
371 void set_turret(double position, double velocity) {
372 turret_position_ = position;
373 turret_velocity_ = velocity;
374 }
375
376 void SendGoal(double left, double right) {
377 auto builder = drivetrain_goal_sender_.MakeBuilder();
378
379 Goal::Builder drivetrain_builder = builder.MakeBuilder<Goal>();
380 drivetrain_builder.add_controller_type(
381 frc971::control_loops::drivetrain::ControllerType::MOTION_PROFILE);
382 drivetrain_builder.add_left_goal(left);
383 drivetrain_builder.add_right_goal(right);
384
385 EXPECT_TRUE(builder.Send(drivetrain_builder.Finish()));
386 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800387
388 private:
James Kuszmaul688a2b02020-02-19 18:26:33 -0800389 void UpdateTurretPosition() {
390 turret_position_ +=
391 turret_velocity_ *
392 aos::time::DurationInSeconds(monotonic_now() - last_turret_update_);
393 last_turret_update_ = monotonic_now();
394 }
395
James Kuszmaul5398fae2020-02-17 16:44:03 -0800396 bool enable_cameras_ = false;
James Kuszmaul688a2b02020-02-19 18:26:33 -0800397 // Whether to make the camera be on the turret or not.
398 bool is_turreted_ = true;
399
400 // The time at which we last incremented turret_position_.
401 monotonic_clock::time_point last_turret_update_ = monotonic_clock::min_time;
402 // Current turret position and velocity. These are set directly by the user in
403 // the test, and if velocity is non-zero, then we will automatically increment
404 // turret_position_ with every timestep.
405 double turret_position_ = 0.0; // rad
406 double turret_velocity_ = 0.0; // rad / sec
James Kuszmaul5398fae2020-02-17 16:44:03 -0800407
408 std::unique_ptr<aos::EventLoop> logger_event_loop_;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800409 std::unique_ptr<aos::logger::Logger> logger_;
410};
411
412// Tests that no camera updates, combined with a perfect model, results in no
413// error.
414TEST_F(LocalizedDrivetrainTest, NoCameraUpdate) {
415 SetEnabled(true);
416 set_enable_cameras(false);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800417 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800418
James Kuszmaul688a2b02020-02-19 18:26:33 -0800419 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800420
James Kuszmaul5398fae2020-02-17 16:44:03 -0800421 RunFor(chrono::seconds(3));
422 VerifyNearGoal();
James Kuszmaul688a2b02020-02-19 18:26:33 -0800423 EXPECT_TRUE(VerifyEstimatorAccurate(5e-4));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800424}
425
James Kuszmaul7f55f072020-03-01 10:21:26 -0800426// Tests that we can drive in a straight line and have things estimate
427// correctly.
428TEST_F(LocalizedDrivetrainTest, NoCameraUpdateStraightLine) {
429 SetEnabled(true);
430 set_enable_cameras(false);
431 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
432
433 SendGoal(1.0, 1.0);
434
435 RunFor(chrono::seconds(1));
436 VerifyNearGoal();
437 // Due to accelerometer drift, the straight-line driving tends to be less
438 // accurate...
Austin Schuhcadb3292021-01-23 20:24:17 -0800439 EXPECT_TRUE(VerifyEstimatorAccurate(0.15));
James Kuszmaul7f55f072020-03-01 10:21:26 -0800440}
441
James Kuszmaul688a2b02020-02-19 18:26:33 -0800442// Tests that camera updates with a perfect models results in no errors.
James Kuszmaul5398fae2020-02-17 16:44:03 -0800443TEST_F(LocalizedDrivetrainTest, PerfectCameraUpdate) {
444 SetEnabled(true);
445 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800446 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800447
James Kuszmaul688a2b02020-02-19 18:26:33 -0800448 SendGoal(-1.0, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800449
James Kuszmaul5398fae2020-02-17 16:44:03 -0800450 RunFor(chrono::seconds(3));
451 VerifyNearGoal();
James Kuszmaul66efe832020-03-16 19:38:33 -0700452 EXPECT_TRUE(VerifyEstimatorAccurate(2e-3));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800453}
454
James Kuszmaul688a2b02020-02-19 18:26:33 -0800455// Tests that camera updates with a constant initial error in the position
James Kuszmaul5398fae2020-02-17 16:44:03 -0800456// results in convergence.
457TEST_F(LocalizedDrivetrainTest, InitialPositionError) {
458 SetEnabled(true);
459 set_enable_cameras(true);
James Kuszmaul688a2b02020-02-19 18:26:33 -0800460 set_camera_is_turreted(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800461 drivetrain_plant_.mutable_state()->topRows(3) +=
462 Eigen::Vector3d(0.1, 0.1, 0.01);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800463
James Kuszmaul688a2b02020-02-19 18:26:33 -0800464 // Confirm that some translational movement does get handled correctly.
465 SendGoal(-0.9, 1.0);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800466
James Kuszmaul5398fae2020-02-17 16:44:03 -0800467 // Give the filters enough time to converge.
468 RunFor(chrono::seconds(10));
469 VerifyNearGoal(5e-3);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800470 EXPECT_TRUE(VerifyEstimatorAccurate(4e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800471}
472
473// Tests that camera updates using a non-turreted camera work.
474TEST_F(LocalizedDrivetrainTest, InitialPositionErrorNoTurret) {
475 SetEnabled(true);
476 set_enable_cameras(true);
477 set_camera_is_turreted(false);
478 drivetrain_plant_.mutable_state()->topRows(3) +=
479 Eigen::Vector3d(0.1, 0.1, 0.01);
480
481 SendGoal(-1.0, 1.0);
482
483 // Give the filters enough time to converge.
484 RunFor(chrono::seconds(10));
485 VerifyNearGoal(5e-3);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800486 EXPECT_TRUE(VerifyEstimatorAccurate(4e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800487}
488
489// Tests that we are able to handle a constant, non-zero turret angle.
490TEST_F(LocalizedDrivetrainTest, NonZeroTurret) {
491 SetEnabled(true);
492 set_enable_cameras(true);
493 set_camera_is_turreted(true);
494 set_turret(1.0, 0.0);
495 drivetrain_plant_.mutable_state()->topRows(3) +=
496 Eigen::Vector3d(0.1, 0.1, 0.0);
497
498 SendGoal(-1.0, 1.0);
499
500 // Give the filters enough time to converge.
501 RunFor(chrono::seconds(10));
502 VerifyNearGoal(5e-3);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800503 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800504}
505
506// Tests that we are able to handle a constant velocity turret.
507TEST_F(LocalizedDrivetrainTest, MovingTurret) {
508 SetEnabled(true);
509 set_enable_cameras(true);
510 set_camera_is_turreted(true);
511 set_turret(0.0, 0.2);
512 drivetrain_plant_.mutable_state()->topRows(3) +=
513 Eigen::Vector3d(0.1, 0.1, 0.0);
514
515 SendGoal(-1.0, 1.0);
516
517 // Give the filters enough time to converge.
518 RunFor(chrono::seconds(10));
519 VerifyNearGoal(5e-3);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800520 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800521}
522
523// Tests that we reject camera measurements when the turret is spinning too
524// fast.
525TEST_F(LocalizedDrivetrainTest, TooFastTurret) {
526 SetEnabled(true);
527 set_enable_cameras(true);
528 set_camera_is_turreted(true);
529 set_turret(0.0, -10.0);
530 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
531 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
532
533 SendGoal(-1.0, 1.0);
534
535 RunFor(chrono::seconds(10));
536 EXPECT_FALSE(VerifyEstimatorAccurate(1e-3));
537 // If we remove the disturbance, we should now be correct.
538 drivetrain_plant_.mutable_state()->topRows(3) -= disturbance;
539 VerifyNearGoal(5e-3);
Austin Schuhcadb3292021-01-23 20:24:17 -0800540 EXPECT_TRUE(VerifyEstimatorAccurate(2e-3));
James Kuszmaul688a2b02020-02-19 18:26:33 -0800541}
542
543// Tests that we don't reject camera measurements when the turret is spinning
544// too fast but we aren't using a camera attached to the turret.
545TEST_F(LocalizedDrivetrainTest, TooFastTurretDoesntAffectFixedCamera) {
546 SetEnabled(true);
547 set_enable_cameras(true);
548 set_camera_is_turreted(false);
549 set_turret(0.0, -10.0);
550 const Eigen::Vector3d disturbance(0.1, 0.1, 0.0);
551 drivetrain_plant_.mutable_state()->topRows(3) += disturbance;
552
553 SendGoal(-1.0, 1.0);
554
555 RunFor(chrono::seconds(10));
556 VerifyNearGoal(5e-3);
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800557 EXPECT_TRUE(VerifyEstimatorAccurate(1e-2));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800558}
559
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700560// Tests that we don't blow up if we stop getting updates for an extended period
561// of time and fall behind on fetching fron the cameras.
562TEST_F(LocalizedDrivetrainTest, FetchersHandleTimeGap) {
563 set_enable_cameras(true);
564 set_send_delay(std::chrono::seconds(0));
565 event_loop_factory()->set_network_delay(std::chrono::nanoseconds(1));
566 test_event_loop_
567 ->AddTimer([this]() { drivetrain_plant_.set_send_messages(false); })
568 ->Setup(test_event_loop_->monotonic_now());
569 test_event_loop_->AddPhasedLoop(
570 [this](int) {
571 auto builder = camera_sender_.MakeBuilder();
572 ImageMatchResultT image;
573 ASSERT_TRUE(
574 builder.Send(ImageMatchResult::Pack(*builder.fbb(), &image)));
575 },
576 std::chrono::milliseconds(20));
577 test_event_loop_
578 ->AddTimer([this]() {
579 drivetrain_plant_.set_send_messages(true);
580 SimulateSensorReset();
581 })
582 ->Setup(test_event_loop_->monotonic_now() + std::chrono::seconds(10));
583
584 RunFor(chrono::seconds(20));
585}
586
James Kuszmaul5398fae2020-02-17 16:44:03 -0800587} // namespace testing
588} // namespace drivetrain
589} // namespace control_loops
590} // namespace y2020