blob: 927eec0f71fa6544b39253c80914d66f2e9b9e96 [file] [log] [blame]
James Kuszmaul5398fae2020-02-17 16:44:03 -08001#include "y2020/control_loops/drivetrain/localizer.h"
2
3#include "y2020/constants.h"
4
5namespace y2020 {
6namespace control_loops {
7namespace drivetrain {
8
9namespace {
10// Converts a flatbuffer TransformationMatrix to an Eigen matrix. Technically,
11// this should be able to do a single memcpy, but the extra verbosity here seems
12// appropriate.
13Eigen::Matrix<double, 4, 4> FlatbufferToTransformationMatrix(
14 const frc971::vision::sift::TransformationMatrix &flatbuffer) {
15 CHECK_EQ(16u, CHECK_NOTNULL(flatbuffer.data())->size());
16 Eigen::Matrix<double, 4, 4> result;
17 result.setIdentity();
18 for (int row = 0; row < 4; ++row) {
19 for (int col = 0; col < 4; ++col) {
20 result(row, col) = (*flatbuffer.data())[row * 4 + col];
21 }
22 }
23 return result;
24}
James Kuszmaul958b21e2020-02-26 21:51:40 -080025
James Kuszmaul5398fae2020-02-17 16:44:03 -080026} // namespace
27
28Localizer::Localizer(
29 aos::EventLoop *event_loop,
30 const frc971::control_loops::drivetrain::DrivetrainConfig<double>
31 &dt_config)
James Kuszmaul958b21e2020-02-26 21:51:40 -080032 : event_loop_(event_loop),
33 dt_config_(dt_config),
34 ekf_(dt_config),
35 clock_offset_fetcher_(
36 event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>(
37 "/aos")) {
James Kuszmaul5398fae2020-02-17 16:44:03 -080038 // TODO(james): This doesn't really need to be a watcher; we could just use a
39 // fetcher for the superstructure status.
40 // This probably should be a Fetcher instead of a Watcher, but this
41 // seems simpler for the time being (although technically it should be
42 // possible to do everything we need to using just a Fetcher without
43 // even maintaining a separate buffer, but that seems overly cute).
44 event_loop_->MakeWatcher("/superstructure",
45 [this](const superstructure::Status &status) {
46 HandleSuperstructureStatus(status);
47 });
48
James Kuszmaul286b4282020-02-26 20:29:32 -080049 event_loop->OnRun([this, event_loop]() {
50 ekf_.ResetInitialState(event_loop->monotonic_now(), Ekf::State::Zero(),
51 ekf_.P());
52 });
53
James Kuszmaul5398fae2020-02-17 16:44:03 -080054 image_fetchers_.emplace_back(
55 event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>(
Austin Schuh6aa77be2020-02-22 21:06:40 -080056 "/pi1/camera"));
James Kuszmaul5398fae2020-02-17 16:44:03 -080057
58 target_selector_.set_has_target(false);
59}
60
61void Localizer::HandleSuperstructureStatus(
62 const y2020::control_loops::superstructure::Status &status) {
63 CHECK(status.has_turret());
64 turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(),
65 status.turret()->velocity()});
66}
67
68Localizer::TurretData Localizer::GetTurretDataForTime(
69 aos::monotonic_clock::time_point time) {
70 if (turret_data_.empty()) {
71 return {};
72 }
73
74 aos::monotonic_clock::duration lowest_time_error =
75 aos::monotonic_clock::duration::max();
76 TurretData best_data_match;
77 for (const auto &sample : turret_data_) {
78 const aos::monotonic_clock::duration time_error =
79 std::chrono::abs(sample.receive_time - time);
80 if (time_error < lowest_time_error) {
81 lowest_time_error = time_error;
82 best_data_match = sample;
83 }
84 }
85 return best_data_match;
86}
87
88void Localizer::Update(const ::Eigen::Matrix<double, 2, 1> &U,
89 aos::monotonic_clock::time_point now,
90 double left_encoder, double right_encoder,
91 double gyro_rate, const Eigen::Vector3d &accel) {
92 for (auto &image_fetcher : image_fetchers_) {
93 while (image_fetcher.FetchNext()) {
94 HandleImageMatch(*image_fetcher);
95 }
96 }
97 ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, U, accel,
98 now);
99}
100
101void Localizer::HandleImageMatch(
102 const frc971::vision::sift::ImageMatchResult &result) {
James Kuszmaul958b21e2020-02-26 21:51:40 -0800103 std::chrono::nanoseconds monotonic_offset(0);
104 clock_offset_fetcher_.Fetch();
105 if (clock_offset_fetcher_.get() != nullptr) {
106 for (const auto connection : *clock_offset_fetcher_->connections()) {
107 if (connection->has_node() && connection->node()->has_name() &&
108 connection->node()->name()->string_view() == "pi1") {
109 monotonic_offset =
110 std::chrono::nanoseconds(connection->monotonic_offset());
111 break;
112 }
113 }
114 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800115 aos::monotonic_clock::time_point capture_time(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800116 std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) -
117 monotonic_offset);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800118 CHECK(result.has_camera_calibration());
119 // Per the ImageMatchResult specification, we can actually determine whether
120 // the camera is the turret camera just from the presence of the
121 // turret_extrinsics member.
122 const bool is_turret = result.camera_calibration()->has_turret_extrinsics();
123 const TurretData turret_data = GetTurretDataForTime(capture_time);
124 // Ignore readings when the turret is spinning too fast, on the assumption
125 // that the odds of screwing up the time compensation are higher.
126 // Note that the current number here is chosen pretty arbitrarily--1 rad / sec
127 // seems reasonable, but may be unnecessarily low or high.
128 constexpr double kMaxTurretVelocity = 1.0;
129 if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) {
130 return;
131 }
132 CHECK(result.camera_calibration()->has_fixed_extrinsics());
133 const Eigen::Matrix<double, 4, 4> fixed_extrinsics =
134 FlatbufferToTransformationMatrix(
135 *result.camera_calibration()->fixed_extrinsics());
136 // Calculate the pose of the camera relative to the robot origin.
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800137 Eigen::Matrix<double, 4, 4> H_robot_camera = fixed_extrinsics;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800138 if (is_turret) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800139 H_robot_camera = H_robot_camera *
James Kuszmaul5398fae2020-02-17 16:44:03 -0800140 frc971::control_loops::TransformationMatrixForYaw(
141 turret_data.position) *
142 FlatbufferToTransformationMatrix(
143 *result.camera_calibration()->turret_extrinsics());
144 }
145
146 if (!result.has_camera_poses()) {
147 return;
148 }
149
150 for (const frc971::vision::sift::CameraPose *vision_result :
151 *result.camera_poses()) {
152 if (!vision_result->has_camera_to_target() ||
153 !vision_result->has_field_to_target()) {
154 continue;
155 }
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800156 const Eigen::Matrix<double, 4, 4> H_camera_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800157 FlatbufferToTransformationMatrix(*vision_result->camera_to_target());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800158 const Eigen::Matrix<double, 4, 4> H_field_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800159 FlatbufferToTransformationMatrix(*vision_result->field_to_target());
160 // Back out the robot position that is implied by the current camera
161 // reading.
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800162 const Pose measured_pose(H_field_target *
163 (H_robot_camera * H_camera_target).inverse());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800164 const Eigen::Matrix<double, 3, 1> Z(measured_pose.rel_pos().x(),
165 measured_pose.rel_pos().y(),
166 measured_pose.rel_theta());
167 // TODO(james): Figure out how to properly handle calculating the
168 // noise. Currently, the values are deliberately tuned so that image updates
169 // will not be trusted overly much. In theory, we should probably also be
170 // populating some cross-correlation terms.
171 // Note that these are the noise standard deviations (they are squared below
172 // to get variances).
173 Eigen::Matrix<double, 3, 1> noises(1.0, 1.0, 0.1);
174 // Augment the noise by the approximate rotational speed of the
175 // camera. This should help account for the fact that, while we are
176 // spinning, slight timing errors in the camera/turret data will tend to
177 // have mutch more drastic effects on the results.
178 noises *= 1.0 + std::abs((right_velocity() - left_velocity()) /
179 (2.0 * dt_config_.robot_radius) +
180 (is_turret ? turret_data.velocity : 0.0));
181 Eigen::Matrix3d R = Eigen::Matrix3d::Zero();
182 R.diagonal() = noises.cwiseAbs2();
183 Eigen::Matrix<double, HybridEkf::kNOutputs, HybridEkf::kNStates> H;
184 H.setZero();
185 H(0, StateIdx::kX) = 1;
186 H(1, StateIdx::kY) = 1;
187 H(2, StateIdx::kTheta) = 1;
188 ekf_.Correct(Z, nullptr, {}, [H, Z](const State &X, const Input &) {
189 Eigen::Vector3d Zhat = H * X;
190 // In order to deal with wrapping of the
191 // angle, calculate an expected angle that is
192 // in the range (Z(2) - pi, Z(2) + pi].
193 const double angle_error =
194 aos::math::NormalizeAngle(
195 X(StateIdx::kTheta) - Z(2));
196 Zhat(2) = Z(2) + angle_error;
197 return Zhat;
198 },
199 [H](const State &) { return H; }, R, capture_time);
200 }
201}
202
203} // namespace drivetrain
204} // namespace control_loops
205} // namespace y2020