blob: 833028953e114d73f0b9f47c42a9b1ae813e0b5e [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 Kuszmaulc6723cf2020-03-01 14:45:59 -080026// Indices of the pis to use.
27const std::array<std::string, 3> kPisToUse{"pi1", "pi2", "pi3"};
28
James Kuszmaul5398fae2020-02-17 16:44:03 -080029} // namespace
30
31Localizer::Localizer(
32 aos::EventLoop *event_loop,
33 const frc971::control_loops::drivetrain::DrivetrainConfig<double>
34 &dt_config)
James Kuszmaul958b21e2020-02-26 21:51:40 -080035 : event_loop_(event_loop),
36 dt_config_(dt_config),
37 ekf_(dt_config),
38 clock_offset_fetcher_(
39 event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>(
40 "/aos")) {
James Kuszmaul5398fae2020-02-17 16:44:03 -080041 // TODO(james): This doesn't really need to be a watcher; we could just use a
42 // fetcher for the superstructure status.
43 // This probably should be a Fetcher instead of a Watcher, but this
44 // seems simpler for the time being (although technically it should be
45 // possible to do everything we need to using just a Fetcher without
46 // even maintaining a separate buffer, but that seems overly cute).
47 event_loop_->MakeWatcher("/superstructure",
48 [this](const superstructure::Status &status) {
49 HandleSuperstructureStatus(status);
50 });
51
James Kuszmaul286b4282020-02-26 20:29:32 -080052 event_loop->OnRun([this, event_loop]() {
53 ekf_.ResetInitialState(event_loop->monotonic_now(), Ekf::State::Zero(),
54 ekf_.P());
55 });
56
James Kuszmaulc6723cf2020-03-01 14:45:59 -080057 for (const auto &pi : kPisToUse) {
58 image_fetchers_.emplace_back(
59 event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>(
60 "/" + pi + "/camera"));
61 }
James Kuszmaul5398fae2020-02-17 16:44:03 -080062
63 target_selector_.set_has_target(false);
64}
65
66void Localizer::HandleSuperstructureStatus(
67 const y2020::control_loops::superstructure::Status &status) {
68 CHECK(status.has_turret());
69 turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(),
70 status.turret()->velocity()});
71}
72
73Localizer::TurretData Localizer::GetTurretDataForTime(
74 aos::monotonic_clock::time_point time) {
75 if (turret_data_.empty()) {
76 return {};
77 }
78
79 aos::monotonic_clock::duration lowest_time_error =
80 aos::monotonic_clock::duration::max();
81 TurretData best_data_match;
82 for (const auto &sample : turret_data_) {
83 const aos::monotonic_clock::duration time_error =
84 std::chrono::abs(sample.receive_time - time);
85 if (time_error < lowest_time_error) {
86 lowest_time_error = time_error;
87 best_data_match = sample;
88 }
89 }
90 return best_data_match;
91}
92
93void Localizer::Update(const ::Eigen::Matrix<double, 2, 1> &U,
94 aos::monotonic_clock::time_point now,
95 double left_encoder, double right_encoder,
96 double gyro_rate, const Eigen::Vector3d &accel) {
James Kuszmaulc6723cf2020-03-01 14:45:59 -080097 for (size_t ii = 0; ii < kPisToUse.size(); ++ii) {
98 auto &image_fetcher = image_fetchers_[ii];
James Kuszmaul5398fae2020-02-17 16:44:03 -080099 while (image_fetcher.FetchNext()) {
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800100 HandleImageMatch(kPisToUse[ii], *image_fetcher);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800101 }
102 }
103 ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, U, accel,
104 now);
105}
106
107void Localizer::HandleImageMatch(
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800108 std::string_view pi, const frc971::vision::sift::ImageMatchResult &result) {
James Kuszmaul958b21e2020-02-26 21:51:40 -0800109 std::chrono::nanoseconds monotonic_offset(0);
110 clock_offset_fetcher_.Fetch();
111 if (clock_offset_fetcher_.get() != nullptr) {
112 for (const auto connection : *clock_offset_fetcher_->connections()) {
113 if (connection->has_node() && connection->node()->has_name() &&
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800114 connection->node()->name()->string_view() == pi) {
James Kuszmaul958b21e2020-02-26 21:51:40 -0800115 monotonic_offset =
116 std::chrono::nanoseconds(connection->monotonic_offset());
117 break;
118 }
119 }
120 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800121 aos::monotonic_clock::time_point capture_time(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800122 std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) -
123 monotonic_offset);
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800124 VLOG(1) << "Got monotonic offset of "
125 << aos::time::DurationInSeconds(monotonic_offset)
126 << " when at time of " << event_loop_->monotonic_now()
127 << " and capture time estimate of " << capture_time;
128 if (capture_time > event_loop_->monotonic_now()) {
129 LOG(WARNING) << "Got camera frame from the future.";
130 return;
131 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800132 CHECK(result.has_camera_calibration());
133 // Per the ImageMatchResult specification, we can actually determine whether
134 // the camera is the turret camera just from the presence of the
135 // turret_extrinsics member.
136 const bool is_turret = result.camera_calibration()->has_turret_extrinsics();
137 const TurretData turret_data = GetTurretDataForTime(capture_time);
138 // Ignore readings when the turret is spinning too fast, on the assumption
139 // that the odds of screwing up the time compensation are higher.
140 // Note that the current number here is chosen pretty arbitrarily--1 rad / sec
141 // seems reasonable, but may be unnecessarily low or high.
142 constexpr double kMaxTurretVelocity = 1.0;
143 if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) {
144 return;
145 }
146 CHECK(result.camera_calibration()->has_fixed_extrinsics());
147 const Eigen::Matrix<double, 4, 4> fixed_extrinsics =
148 FlatbufferToTransformationMatrix(
149 *result.camera_calibration()->fixed_extrinsics());
150 // Calculate the pose of the camera relative to the robot origin.
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800151 Eigen::Matrix<double, 4, 4> H_robot_camera = fixed_extrinsics;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800152 if (is_turret) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800153 H_robot_camera = H_robot_camera *
James Kuszmaul5398fae2020-02-17 16:44:03 -0800154 frc971::control_loops::TransformationMatrixForYaw(
155 turret_data.position) *
156 FlatbufferToTransformationMatrix(
157 *result.camera_calibration()->turret_extrinsics());
158 }
159
160 if (!result.has_camera_poses()) {
161 return;
162 }
163
164 for (const frc971::vision::sift::CameraPose *vision_result :
165 *result.camera_poses()) {
166 if (!vision_result->has_camera_to_target() ||
167 !vision_result->has_field_to_target()) {
168 continue;
169 }
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800170 const Eigen::Matrix<double, 4, 4> H_camera_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800171 FlatbufferToTransformationMatrix(*vision_result->camera_to_target());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800172 const Eigen::Matrix<double, 4, 4> H_field_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800173 FlatbufferToTransformationMatrix(*vision_result->field_to_target());
174 // Back out the robot position that is implied by the current camera
175 // reading.
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800176 const Pose measured_pose(H_field_target *
177 (H_robot_camera * H_camera_target).inverse());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800178 const Eigen::Matrix<double, 3, 1> Z(measured_pose.rel_pos().x(),
179 measured_pose.rel_pos().y(),
180 measured_pose.rel_theta());
181 // TODO(james): Figure out how to properly handle calculating the
182 // noise. Currently, the values are deliberately tuned so that image updates
183 // will not be trusted overly much. In theory, we should probably also be
184 // populating some cross-correlation terms.
185 // Note that these are the noise standard deviations (they are squared below
186 // to get variances).
187 Eigen::Matrix<double, 3, 1> noises(1.0, 1.0, 0.1);
188 // Augment the noise by the approximate rotational speed of the
189 // camera. This should help account for the fact that, while we are
190 // spinning, slight timing errors in the camera/turret data will tend to
191 // have mutch more drastic effects on the results.
192 noises *= 1.0 + std::abs((right_velocity() - left_velocity()) /
193 (2.0 * dt_config_.robot_radius) +
194 (is_turret ? turret_data.velocity : 0.0));
195 Eigen::Matrix3d R = Eigen::Matrix3d::Zero();
196 R.diagonal() = noises.cwiseAbs2();
197 Eigen::Matrix<double, HybridEkf::kNOutputs, HybridEkf::kNStates> H;
198 H.setZero();
199 H(0, StateIdx::kX) = 1;
200 H(1, StateIdx::kY) = 1;
201 H(2, StateIdx::kTheta) = 1;
202 ekf_.Correct(Z, nullptr, {}, [H, Z](const State &X, const Input &) {
203 Eigen::Vector3d Zhat = H * X;
204 // In order to deal with wrapping of the
205 // angle, calculate an expected angle that is
206 // in the range (Z(2) - pi, Z(2) + pi].
207 const double angle_error =
208 aos::math::NormalizeAngle(
209 X(StateIdx::kTheta) - Z(2));
210 Zhat(2) = Z(2) + angle_error;
211 return Zhat;
212 },
213 [H](const State &) { return H; }, R, capture_time);
214 }
215}
216
217} // namespace drivetrain
218} // namespace control_loops
219} // namespace y2020