blob: 1e33826b639da8f317aa711c61162aa0a7ca610a [file] [log] [blame]
James Kuszmaul1798c072022-02-13 15:32:11 -08001#include "y2022/control_loops/drivetrain/localizer.h"
2
3#include <queue>
4
5#include "aos/events/logging/log_writer.h"
6#include "aos/network/message_bridge_server_generated.h"
7#include "aos/network/team_number.h"
8#include "aos/network/testing_time_converter.h"
9#include "frc971/control_loops/control_loop_test.h"
10#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 Kuszmaul51fa1ae2022-02-26 00:49:57 -080013#include "y2022/localizer/localizer_output_generated.h"
James Kuszmaul1798c072022-02-13 15:32:11 -080014#include "gtest/gtest.h"
15#include "y2022/control_loops/drivetrain/drivetrain_base.h"
16
17DEFINE_string(output_folder, "",
18 "If set, logs all channels to the provided logfile.");
19
20namespace y2022 {
21namespace control_loops {
22namespace drivetrain {
23namespace testing {
24
25using frc971::control_loops::drivetrain::DrivetrainConfig;
26using frc971::control_loops::drivetrain::Goal;
27using frc971::control_loops::drivetrain::LocalizerControl;
28
29namespace {
30DrivetrainConfig<double> GetTest2022DrivetrainConfig() {
31 DrivetrainConfig<double> config = GetDrivetrainConfig();
32 return config;
33}
34}
35
36namespace chrono = std::chrono;
37using aos::monotonic_clock;
38using frc971::control_loops::drivetrain::DrivetrainLoop;
39using frc971::control_loops::drivetrain::testing::DrivetrainSimulation;
40
41// TODO(james): Make it so this actually tests the full system of the localizer.
42class LocalizedDrivetrainTest : public frc971::testing::ControlLoopTest {
43 protected:
44 // We must use the 2022 drivetrain config so that we don't have to deal
45 // with shifting:
46 LocalizedDrivetrainTest()
47 : frc971::testing::ControlLoopTest(
48 aos::configuration::ReadConfig(
49 "y2022/control_loops/drivetrain/simulation_config.json"),
50 GetTest2022DrivetrainConfig().dt),
51 roborio_(aos::configuration::GetNode(configuration(), "roborio")),
52 imu_(aos::configuration::GetNode(configuration(), "imu")),
53 test_event_loop_(MakeEventLoop("test", roborio_)),
54 imu_test_event_loop_(MakeEventLoop("test", imu_)),
55 drivetrain_goal_sender_(
56 test_event_loop_->MakeSender<Goal>("/drivetrain")),
57 localizer_output_sender_(
58 imu_test_event_loop_->MakeSender<frc971::controls::LocalizerOutput>(
59 "/localizer")),
60 drivetrain_goal_fetcher_(
61 test_event_loop_->MakeFetcher<Goal>("/drivetrain")),
62 drivetrain_status_fetcher_(
63 test_event_loop_
64 ->MakeFetcher<frc971::control_loops::drivetrain::Status>(
65 "/drivetrain")),
66 localizer_control_sender_(
67 test_event_loop_->MakeSender<LocalizerControl>("/drivetrain")),
68 drivetrain_event_loop_(MakeEventLoop("drivetrain", roborio_)),
69 dt_config_(GetTest2022DrivetrainConfig()),
70 localizer_(drivetrain_event_loop_.get(), dt_config_),
71 drivetrain_(dt_config_, drivetrain_event_loop_.get(), &localizer_),
72 drivetrain_plant_event_loop_(MakeEventLoop("plant", roborio_)),
73 drivetrain_plant_imu_event_loop_(MakeEventLoop("plant", imu_)),
74 drivetrain_plant_(drivetrain_plant_event_loop_.get(),
75 drivetrain_plant_imu_event_loop_.get(), dt_config_,
76 std::chrono::microseconds(500)) {
77 set_team_id(frc971::control_loops::testing::kTeamNumber);
78 set_battery_voltage(12.0);
79
80 if (!FLAGS_output_folder.empty()) {
81 logger_event_loop_ = MakeEventLoop("logger", roborio_);
82 logger_ = std::make_unique<aos::logger::Logger>(logger_event_loop_.get());
83 logger_->StartLoggingOnRun(FLAGS_output_folder);
84 }
85
86 test_event_loop_->OnRun([this]() { SetStartingPosition({3.0, 2.0, 0.0}); });
87
88 imu_test_event_loop_
89 ->AddTimer([this]() {
90 auto builder = localizer_output_sender_.MakeBuilder();
91 frc971::controls::LocalizerOutput::Builder output_builder =
92 builder.MakeBuilder<frc971::controls::LocalizerOutput>();
93 output_builder.add_monotonic_timestamp_ns(
94 imu_test_event_loop_->monotonic_now().time_since_epoch().count());
95 output_builder.add_x(drivetrain_plant_.state()(0));
96 output_builder.add_y(drivetrain_plant_.state()(1));
97 output_builder.add_theta(drivetrain_plant_.state()(2));
98 })
99 ->Setup(imu_test_event_loop_->monotonic_now(),
100 std::chrono::milliseconds(5));
101 }
102
103 virtual ~LocalizedDrivetrainTest() override {}
104
105 void SetStartingPosition(const Eigen::Matrix<double, 3, 1> &xytheta) {
106 *drivetrain_plant_.mutable_state() << xytheta.x(), xytheta.y(),
107 xytheta(2, 0), 0.0, 0.0;
108 Eigen::Matrix<double, Localizer::HybridEkf::kNStates, 1> localizer_state;
109 localizer_state.setZero();
110 localizer_state.block<3, 1>(0, 0) = xytheta;
111 localizer_.Reset(monotonic_now(), localizer_state);
112 }
113
114 void VerifyNearGoal(double eps = 1e-2) {
115 drivetrain_goal_fetcher_.Fetch();
116 EXPECT_NEAR(drivetrain_goal_fetcher_->left_goal(),
117 drivetrain_plant_.GetLeftPosition(), eps);
118 EXPECT_NEAR(drivetrain_goal_fetcher_->right_goal(),
119 drivetrain_plant_.GetRightPosition(), eps);
120 }
121
122 ::testing::AssertionResult IsNear(double expected, double actual,
123 double epsilon) {
124 if (std::abs(expected - actual) < epsilon) {
125 return ::testing::AssertionSuccess();
126 } else {
127 return ::testing::AssertionFailure()
128 << "Expected " << expected << " but got " << actual
129 << " with a max difference of " << epsilon
130 << " and an actual difference of " << std::abs(expected - actual);
131 }
132 }
133 ::testing::AssertionResult VerifyEstimatorAccurate(double eps) {
134 const Eigen::Matrix<double, 5, 1> true_state = drivetrain_plant_.state();
135 ::testing::AssertionResult result(true);
136 if (!(result = IsNear(localizer_.x(), true_state(0), eps))) {
137 return result;
138 }
139 if (!(result = IsNear(localizer_.y(), true_state(1), eps))) {
140 return result;
141 }
142 if (!(result = IsNear(localizer_.theta(), true_state(2), eps))) {
143 return result;
144 }
145 if (!(result = IsNear(localizer_.left_velocity(), true_state(3), eps))) {
146 return result;
147 }
148 if (!(result = IsNear(localizer_.right_velocity(), true_state(4), eps))) {
149 return result;
150 }
151 return result;
152 }
153
154 const aos::Node *const roborio_;
155 const aos::Node *const imu_;
156
157 std::unique_ptr<aos::EventLoop> test_event_loop_;
158 std::unique_ptr<aos::EventLoop> imu_test_event_loop_;
159 aos::Sender<Goal> drivetrain_goal_sender_;
160 aos::Sender<frc971::controls::LocalizerOutput> localizer_output_sender_;
161 aos::Fetcher<Goal> drivetrain_goal_fetcher_;
162 aos::Fetcher<frc971::control_loops::drivetrain::Status>
163 drivetrain_status_fetcher_;
164 aos::Sender<LocalizerControl> localizer_control_sender_;
165
166 std::unique_ptr<aos::EventLoop> drivetrain_event_loop_;
167 const frc971::control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
168
169 Localizer localizer_;
170 DrivetrainLoop drivetrain_;
171
172 std::unique_ptr<aos::EventLoop> drivetrain_plant_event_loop_;
173 std::unique_ptr<aos::EventLoop> drivetrain_plant_imu_event_loop_;
174 DrivetrainSimulation drivetrain_plant_;
175
176 void SendGoal(double left, double right) {
177 auto builder = drivetrain_goal_sender_.MakeBuilder();
178
179 Goal::Builder drivetrain_builder = builder.MakeBuilder<Goal>();
180 drivetrain_builder.add_controller_type(
181 frc971::control_loops::drivetrain::ControllerType::MOTION_PROFILE);
182 drivetrain_builder.add_left_goal(left);
183 drivetrain_builder.add_right_goal(right);
184
185 EXPECT_EQ(builder.Send(drivetrain_builder.Finish()),
186 aos::RawSender::Error::kOk);
187 }
188
189 private:
190 std::unique_ptr<aos::EventLoop> logger_event_loop_;
191 std::unique_ptr<aos::logger::Logger> logger_;
192};
193
194TEST_F(LocalizedDrivetrainTest, Nominal) {
195 SetEnabled(true);
196 EXPECT_TRUE(VerifyEstimatorAccurate(1e-7));
197
198 SendGoal(-1.0, 1.0);
199
200 RunFor(chrono::seconds(10));
201 VerifyNearGoal();
202 EXPECT_TRUE(VerifyEstimatorAccurate(5e-3));
203}
204
205} // namespace testing
206} // namespace drivetrain
207} // namespace control_loops
208} // namespace y2022