blob: b8463d6329971bfff347b4b2746ce5120cc06294 [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
49 image_fetchers_.emplace_back(
50 event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>(
Austin Schuh6aa77be2020-02-22 21:06:40 -080051 "/pi1/camera"));
James Kuszmaul5398fae2020-02-17 16:44:03 -080052
53 target_selector_.set_has_target(false);
54}
55
56void Localizer::HandleSuperstructureStatus(
57 const y2020::control_loops::superstructure::Status &status) {
58 CHECK(status.has_turret());
59 turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(),
60 status.turret()->velocity()});
61}
62
63Localizer::TurretData Localizer::GetTurretDataForTime(
64 aos::monotonic_clock::time_point time) {
65 if (turret_data_.empty()) {
66 return {};
67 }
68
69 aos::monotonic_clock::duration lowest_time_error =
70 aos::monotonic_clock::duration::max();
71 TurretData best_data_match;
72 for (const auto &sample : turret_data_) {
73 const aos::monotonic_clock::duration time_error =
74 std::chrono::abs(sample.receive_time - time);
75 if (time_error < lowest_time_error) {
76 lowest_time_error = time_error;
77 best_data_match = sample;
78 }
79 }
80 return best_data_match;
81}
82
83void Localizer::Update(const ::Eigen::Matrix<double, 2, 1> &U,
84 aos::monotonic_clock::time_point now,
85 double left_encoder, double right_encoder,
86 double gyro_rate, const Eigen::Vector3d &accel) {
87 for (auto &image_fetcher : image_fetchers_) {
88 while (image_fetcher.FetchNext()) {
89 HandleImageMatch(*image_fetcher);
90 }
91 }
92 ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, U, accel,
93 now);
94}
95
96void Localizer::HandleImageMatch(
97 const frc971::vision::sift::ImageMatchResult &result) {
James Kuszmaul958b21e2020-02-26 21:51:40 -080098 std::chrono::nanoseconds monotonic_offset(0);
99 clock_offset_fetcher_.Fetch();
100 if (clock_offset_fetcher_.get() != nullptr) {
101 for (const auto connection : *clock_offset_fetcher_->connections()) {
102 if (connection->has_node() && connection->node()->has_name() &&
103 connection->node()->name()->string_view() == "pi1") {
104 monotonic_offset =
105 std::chrono::nanoseconds(connection->monotonic_offset());
106 break;
107 }
108 }
109 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800110 aos::monotonic_clock::time_point capture_time(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800111 std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) -
112 monotonic_offset);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800113 CHECK(result.has_camera_calibration());
114 // Per the ImageMatchResult specification, we can actually determine whether
115 // the camera is the turret camera just from the presence of the
116 // turret_extrinsics member.
117 const bool is_turret = result.camera_calibration()->has_turret_extrinsics();
118 const TurretData turret_data = GetTurretDataForTime(capture_time);
119 // Ignore readings when the turret is spinning too fast, on the assumption
120 // that the odds of screwing up the time compensation are higher.
121 // Note that the current number here is chosen pretty arbitrarily--1 rad / sec
122 // seems reasonable, but may be unnecessarily low or high.
123 constexpr double kMaxTurretVelocity = 1.0;
124 if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) {
125 return;
126 }
127 CHECK(result.camera_calibration()->has_fixed_extrinsics());
128 const Eigen::Matrix<double, 4, 4> fixed_extrinsics =
129 FlatbufferToTransformationMatrix(
130 *result.camera_calibration()->fixed_extrinsics());
131 // Calculate the pose of the camera relative to the robot origin.
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800132 Eigen::Matrix<double, 4, 4> H_robot_camera = fixed_extrinsics;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800133 if (is_turret) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800134 H_robot_camera = H_robot_camera *
James Kuszmaul5398fae2020-02-17 16:44:03 -0800135 frc971::control_loops::TransformationMatrixForYaw(
136 turret_data.position) *
137 FlatbufferToTransformationMatrix(
138 *result.camera_calibration()->turret_extrinsics());
139 }
140
141 if (!result.has_camera_poses()) {
142 return;
143 }
144
145 for (const frc971::vision::sift::CameraPose *vision_result :
146 *result.camera_poses()) {
147 if (!vision_result->has_camera_to_target() ||
148 !vision_result->has_field_to_target()) {
149 continue;
150 }
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800151 const Eigen::Matrix<double, 4, 4> H_camera_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800152 FlatbufferToTransformationMatrix(*vision_result->camera_to_target());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800153 const Eigen::Matrix<double, 4, 4> H_field_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800154 FlatbufferToTransformationMatrix(*vision_result->field_to_target());
155 // Back out the robot position that is implied by the current camera
156 // reading.
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800157 const Pose measured_pose(H_field_target *
158 (H_robot_camera * H_camera_target).inverse());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800159 const Eigen::Matrix<double, 3, 1> Z(measured_pose.rel_pos().x(),
160 measured_pose.rel_pos().y(),
161 measured_pose.rel_theta());
162 // TODO(james): Figure out how to properly handle calculating the
163 // noise. Currently, the values are deliberately tuned so that image updates
164 // will not be trusted overly much. In theory, we should probably also be
165 // populating some cross-correlation terms.
166 // Note that these are the noise standard deviations (they are squared below
167 // to get variances).
168 Eigen::Matrix<double, 3, 1> noises(1.0, 1.0, 0.1);
169 // Augment the noise by the approximate rotational speed of the
170 // camera. This should help account for the fact that, while we are
171 // spinning, slight timing errors in the camera/turret data will tend to
172 // have mutch more drastic effects on the results.
173 noises *= 1.0 + std::abs((right_velocity() - left_velocity()) /
174 (2.0 * dt_config_.robot_radius) +
175 (is_turret ? turret_data.velocity : 0.0));
176 Eigen::Matrix3d R = Eigen::Matrix3d::Zero();
177 R.diagonal() = noises.cwiseAbs2();
178 Eigen::Matrix<double, HybridEkf::kNOutputs, HybridEkf::kNStates> H;
179 H.setZero();
180 H(0, StateIdx::kX) = 1;
181 H(1, StateIdx::kY) = 1;
182 H(2, StateIdx::kTheta) = 1;
183 ekf_.Correct(Z, nullptr, {}, [H, Z](const State &X, const Input &) {
184 Eigen::Vector3d Zhat = H * X;
185 // In order to deal with wrapping of the
186 // angle, calculate an expected angle that is
187 // in the range (Z(2) - pi, Z(2) + pi].
188 const double angle_error =
189 aos::math::NormalizeAngle(
190 X(StateIdx::kTheta) - Z(2));
191 Zhat(2) = Z(2) + angle_error;
192 return Zhat;
193 },
194 [H](const State &) { return H; }, R, capture_time);
195 }
196}
197
198} // namespace drivetrain
199} // namespace control_loops
200} // namespace y2020