blob: 3f2fbbc1d91eed86672efdbbe148bd6f59573ab8 [file] [log] [blame]
Brian Silverman2ccf8c52016-03-15 00:22:26 -04001#include <netdb.h>
Parker Schuh2cd173d2017-01-28 00:12:01 -08002#include <stdlib.h>
Brian Silverman2ccf8c52016-03-15 00:22:26 -04003#include <unistd.h>
4
Brian Silvermanbc831182016-04-16 02:06:09 -04005#include <array>
Brian Silvermanbc831182016-04-16 02:06:09 -04006#include <atomic>
Austin Schuhfb5f7de2016-11-26 15:15:19 -08007#include <chrono>
Brian Silvermanbc831182016-04-16 02:06:09 -04008#include <limits>
Austin Schuhfb5f7de2016-11-26 15:15:19 -08009#include <memory>
10#include <thread>
11#include <vector>
Brian Silverman2ccf8c52016-03-15 00:22:26 -040012
John Park33858a32018-09-28 23:05:48 -070013#include "aos/logging/logging.h"
14#include "aos/logging/queue_logging.h"
15#include "aos/mutex/mutex.h"
16#include "aos/time/time.h"
Parker Schuh2cd173d2017-01-28 00:12:01 -080017#include "aos/linux_code/init.h"
18#include "aos/vision/events/udp.h"
Brian Silvermanbc831182016-04-16 02:06:09 -040019
20#include "frc971/control_loops/drivetrain/drivetrain.q.h"
Brian Silverman2ccf8c52016-03-15 00:22:26 -040021
Parker Schuh2cd173d2017-01-28 00:12:01 -080022#include "y2016/constants.h"
23#include "y2016/vision/stereo_geometry.h"
Brian Silverman2ccf8c52016-03-15 00:22:26 -040024#include "y2016/vision/vision.q.h"
25#include "y2016/vision/vision_data.pb.h"
Brian Silverman2ccf8c52016-03-15 00:22:26 -040026
27namespace y2016 {
28namespace vision {
29
Austin Schuhfb5f7de2016-11-26 15:15:19 -080030namespace chrono = ::std::chrono;
31using ::aos::monotonic_clock;
32
Austin Schuh11945742016-04-13 22:18:36 -070033::aos::vision::Vector<2> CreateCenterFromTarget(double lx, double ly, double rx,
34 double ry) {
ben54dbccb2016-03-20 14:42:28 -070035 return ::aos::vision::Vector<2>((lx + rx) / 2.0, (ly + ry) / 2.0);
36}
37
38double TargetWidth(double lx, double ly, double rx, double ry) {
39 double dx = lx - rx;
40 double dy = ly - ry;
Austin Schuh098e4872016-03-20 16:51:24 -070041 return ::std::hypot(dx, dy);
ben54dbccb2016-03-20 14:42:28 -070042}
43
44void SelectTargets(const VisionData &left_target,
45 const VisionData &right_target,
46 ::aos::vision::Vector<2> *center_left,
Austin Schuh6bf73052016-04-20 20:20:25 -070047 ::aos::vision::Vector<2> *center_right, double *angle_left,
48 double *angle_right) {
ben54dbccb2016-03-20 14:42:28 -070049 // No good targets. Let the caller decide defaults.
50 if (right_target.target_size() == 0 || left_target.target_size() == 0) {
51 return;
52 }
53
54 // Only one option, we have to go with it.
55 if (right_target.target_size() == 1 && left_target.target_size() == 1) {
56 *center_left =
57 CreateCenterFromTarget(left_target.target(0).left_corner_x(),
58 left_target.target(0).left_corner_y(),
59 left_target.target(0).right_corner_x(),
60 left_target.target(0).right_corner_y());
61 *center_right =
62 CreateCenterFromTarget(right_target.target(0).left_corner_x(),
63 right_target.target(0).left_corner_y(),
64 right_target.target(0).right_corner_x(),
65 right_target.target(0).right_corner_y());
66 return;
67 }
68
69 // Now we have to make a decision.
Austin Schuh9f59c8a2016-03-20 21:09:05 -070070 double min_angle = -1.0;
ben54dbccb2016-03-20 14:42:28 -070071 int left_index = 0;
72 // First pick the widest target from the left.
73 for (int i = 0; i < left_target.target_size(); i++) {
Austin Schuh9f59c8a2016-03-20 21:09:05 -070074 const double h = left_target.target(i).left_corner_y() -
75 left_target.target(i).right_corner_y();
76 const double wid1 = TargetWidth(left_target.target(i).left_corner_x(),
77 left_target.target(i).left_corner_y(),
78 left_target.target(i).right_corner_x(),
79 left_target.target(i).right_corner_y());
80 const double angle = h / wid1;
81 if (min_angle == -1.0 || ::std::abs(angle) < ::std::abs(min_angle)) {
82 min_angle = angle;
Austin Schuh6bf73052016-04-20 20:20:25 -070083 *angle_left = angle;
ben54dbccb2016-03-20 14:42:28 -070084 left_index = i;
85 }
86 }
87 // Calculate the angle of the bottom edge for the left.
88 double h = left_target.target(left_index).left_corner_y() -
89 left_target.target(left_index).right_corner_y();
Austin Schuh9f59c8a2016-03-20 21:09:05 -070090
91 double good_ang = min_angle;
ben54dbccb2016-03-20 14:42:28 -070092 double min_ang_err = -1.0;
93 int right_index = -1;
Austin Schuh11945742016-04-13 22:18:36 -070094 // Now pick the bottom edge angle from the right that lines up best with the
95 // left.
ben54dbccb2016-03-20 14:42:28 -070096 for (int j = 0; j < right_target.target_size(); j++) {
97 double wid2 = TargetWidth(right_target.target(j).left_corner_x(),
Austin Schuh11945742016-04-13 22:18:36 -070098 right_target.target(j).left_corner_y(),
99 right_target.target(j).right_corner_x(),
100 right_target.target(j).right_corner_y());
ben54dbccb2016-03-20 14:42:28 -0700101 h = right_target.target(j).left_corner_y() -
102 right_target.target(j).right_corner_y();
Austin Schuh11945742016-04-13 22:18:36 -0700103 double ang = h / wid2;
ben54dbccb2016-03-20 14:42:28 -0700104 double ang_err = ::std::abs(good_ang - ang);
105 if (min_ang_err == -1.0 || min_ang_err > ang_err) {
106 min_ang_err = ang_err;
107 right_index = j;
Austin Schuh6bf73052016-04-20 20:20:25 -0700108 *angle_right = ang;
ben54dbccb2016-03-20 14:42:28 -0700109 }
110 }
111
112 *center_left =
113 CreateCenterFromTarget(left_target.target(left_index).left_corner_x(),
114 left_target.target(left_index).left_corner_y(),
115 left_target.target(left_index).right_corner_x(),
116 left_target.target(left_index).right_corner_y());
117 *center_right =
118 CreateCenterFromTarget(right_target.target(right_index).left_corner_x(),
119 right_target.target(right_index).left_corner_y(),
120 right_target.target(right_index).right_corner_x(),
121 right_target.target(right_index).right_corner_y());
122}
123
Austin Schuh11945742016-04-13 22:18:36 -0700124class CameraHandler {
125 public:
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800126 void Received(const VisionData &target, monotonic_clock::time_point now) {
Austin Schuh11945742016-04-13 22:18:36 -0700127 if (current_.received) {
128 last_ = current_;
129 }
130 current_.target = target;
131 current_.rx_time = now;
Austin Schuh6fe1d512016-04-24 19:12:04 -0700132 current_.capture_time = now -
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800133 chrono::nanoseconds(target.send_timestamp() -
134 target.image_timestamp()) +
Austin Schuh6fe1d512016-04-24 19:12:04 -0700135 // It takes a bit to shoot a frame. Push the frame
136 // further back in time.
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800137 chrono::milliseconds(10);
Austin Schuh11945742016-04-13 22:18:36 -0700138 current_.received = true;
139 }
140
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800141 void CheckStale(monotonic_clock::time_point now) {
142 if (now > current_.rx_time + chrono::milliseconds(50)) {
Austin Schuh11945742016-04-13 22:18:36 -0700143 current_.received = false;
144 last_.received = false;
145 }
146 }
147
148 bool received_both() const { return current_.received && last_.received; }
149
150 bool is_valid() const {
151 return current_.target.target_size() > 0 && last_.target.target_size() > 0;
152 }
153
154 const VisionData &target() const { return current_.target; }
155 const VisionData &last_target() const { return last_.target; }
156
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800157 monotonic_clock::time_point capture_time() const {
158 return current_.capture_time;
159 }
160 monotonic_clock::time_point last_capture_time() const {
161 return last_.capture_time;
162 }
Austin Schuh11945742016-04-13 22:18:36 -0700163
164 private:
165 struct TargetWithTimes {
166 VisionData target;
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800167 monotonic_clock::time_point rx_time{monotonic_clock::epoch()};
168 monotonic_clock::time_point capture_time{monotonic_clock::epoch()};
Austin Schuh11945742016-04-13 22:18:36 -0700169 bool received = false;
170 };
171
172 TargetWithTimes current_;
173 TargetWithTimes last_;
174};
175
Austin Schuh6bf73052016-04-20 20:20:25 -0700176void CalculateFiltered(const CameraHandler &older, const CameraHandler &newer,
177 const ::aos::vision::Vector<2> &newer_center,
178 const ::aos::vision::Vector<2> &last_newer_center,
179 double angle, double last_angle,
180 ::aos::vision::Vector<2> *interpolated_result,
181 double *interpolated_angle) {
Parker Schuh2cd173d2017-01-28 00:12:01 -0800182 const double age_ratio = chrono::duration_cast<chrono::duration<double>>(
183 older.capture_time() - newer.last_capture_time())
184 .count() /
185 chrono::duration_cast<chrono::duration<double>>(
186 newer.capture_time() - newer.last_capture_time())
187 .count();
Austin Schuh6bf73052016-04-20 20:20:25 -0700188 interpolated_result->Set(
Austin Schuh11945742016-04-13 22:18:36 -0700189 newer_center.x() * age_ratio + (1 - age_ratio) * last_newer_center.x(),
190 newer_center.y() * age_ratio + (1 - age_ratio) * last_newer_center.y());
Austin Schuh6bf73052016-04-20 20:20:25 -0700191
192 *interpolated_angle = angle * age_ratio + (1 - age_ratio) * last_angle;
Austin Schuh11945742016-04-13 22:18:36 -0700193}
ben54dbccb2016-03-20 14:42:28 -0700194
Brian Silvermanbc831182016-04-16 02:06:09 -0400195// Handles calculating drivetrain offsets.
196class DrivetrainOffsetCalculator {
197 public:
198 // To be called by ::std::thread.
199 void operator()() {
200 auto &status = ::frc971::control_loops::drivetrain_queue.status;
201 while (run_) {
202 status.FetchAnother();
203
204 ::aos::MutexLocker locker(&lock_);
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800205 data_[data_index_].time = status->sent_time;
Brian Silvermanbc831182016-04-16 02:06:09 -0400206 data_[data_index_].left = status->estimated_left_position;
207 data_[data_index_].right = status->estimated_right_position;
208 ++data_index_;
209 if (data_index_ == data_.size()) data_index_ = 0;
210 if (valid_data_ < data_.size()) ++valid_data_;
211 }
212 }
213
214 // Takes a vision status message with everything except
215 // drivetrain_{left,right}_position set and sets those.
216 // Returns false if it doesn't have enough data to fill them out.
217 bool CompleteVisionStatus(::y2016::vision::VisionStatus *status) {
218 if (valid_data_ == 0) return false;
219
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800220 const monotonic_clock::time_point capture_time =
221 monotonic_clock::time_point(chrono::nanoseconds(status->target_time));
Brian Silvermanbc831182016-04-16 02:06:09 -0400222 DrivetrainData before, after;
223 FindBeforeAfter(&before, &after, capture_time);
224
225 if (before.time == after.time) {
226 status->drivetrain_left_position = before.left;
227 status->drivetrain_right_position = before.right;
228 } else {
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800229 const double age_ratio = chrono::duration_cast<chrono::duration<double>>(
Parker Schuh2cd173d2017-01-28 00:12:01 -0800230 capture_time - before.time)
231 .count() /
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800232 chrono::duration_cast<chrono::duration<double>>(
Parker Schuh2cd173d2017-01-28 00:12:01 -0800233 after.time - before.time)
234 .count();
Brian Silvermanbc831182016-04-16 02:06:09 -0400235 status->drivetrain_left_position =
236 before.left * (1 - age_ratio) + after.left * age_ratio;
237 status->drivetrain_right_position =
238 before.right * (1 - age_ratio) + after.right * age_ratio;
239 }
240
241 return true;
242 }
243
244 void Quit() { run_ = false; }
245
246 private:
247 struct DrivetrainData {
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800248 monotonic_clock::time_point time;
Brian Silvermanbc831182016-04-16 02:06:09 -0400249 double left, right;
250 };
251
252 // Fills out before and after with the data surrounding capture_time.
253 // They might be identical if that's the closest approximation.
254 // Do not call this if valid_data_ is 0.
255 void FindBeforeAfter(DrivetrainData *before, DrivetrainData *after,
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800256 monotonic_clock::time_point capture_time) {
Brian Silvermanbc831182016-04-16 02:06:09 -0400257 ::aos::MutexLocker locker(&lock_);
258 size_t location = 0;
259 while (true) {
260 // We hit the end of our data. Just fill them both out as the last data
261 // point.
262 if (location >= valid_data_) {
263 *before = *after =
264 data_[previous_index((valid_data_ + data_index_) % data_.size())];
265 return;
266 }
267
268 // The index into data_ corresponding to location positions after
269 // (data_index_ - 1).
270 const size_t index = previous_index(location + data_index_);
271
272 // If we've found the one we want.
273 if (data_[index].time > capture_time) {
274 *after = data_[index];
275 if (location == 0) {
276 // If this is the first one and it's already after, just return the
277 // same thing for both.
278 *before = data_[index];
279 } else {
280 *before = data_[previous_index(index)];
281 }
282 return;
283 }
284
285 ++location;
286 }
287 }
288
289 size_t previous_index(size_t index) const {
290 if (index == 0) {
291 return data_.size() - 1;
292 } else {
293 return index - 1;
294 }
295 }
296
297 ::std::array<DrivetrainData, 200> data_;
298 // The index into data_ the next data point is going at.
299 size_t data_index_ = 0;
300 // How many elemets of data_ are valid.
301 size_t valid_data_ = 0;
302
303 ::aos::Mutex lock_;
304
305 ::std::atomic<bool> run_{true};
306};
307
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400308void Main() {
309 StereoGeometry stereo(constants::GetValues().vision_name);
310 LOG(INFO, "calibration: %s\n",
311 stereo.calibration().ShortDebugString().c_str());
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400312
Brian Silvermanbc831182016-04-16 02:06:09 -0400313 DrivetrainOffsetCalculator drivetrain_offset;
314 ::std::thread drivetrain_offset_thread(::std::ref(drivetrain_offset));
315
Austin Schuh11945742016-04-13 22:18:36 -0700316 CameraHandler left;
317 CameraHandler right;
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700318
Parker Schuh2cd173d2017-01-28 00:12:01 -0800319 ::aos::events::RXUdpSocket recv(8080);
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700320 char rawData[65507];
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700321
322 while (true) {
323 // TODO(austin): Don't malloc.
324 VisionData target;
325 int size = recv.Recv(rawData, 65507);
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800326 monotonic_clock::time_point now = monotonic_clock::now();
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700327
328 if (target.ParseFromArray(rawData, size)) {
329 if (target.camera_index() == 0) {
Austin Schuh11945742016-04-13 22:18:36 -0700330 left.Received(target, now);
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700331 } else {
Austin Schuh11945742016-04-13 22:18:36 -0700332 right.Received(target, now);
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400333 }
334 } else {
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700335 LOG(ERROR, "oh noes: parse error\n");
336 continue;
337 }
338
Austin Schuh11945742016-04-13 22:18:36 -0700339 left.CheckStale(now);
340 right.CheckStale(now);
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400341
Austin Schuh11945742016-04-13 22:18:36 -0700342 if (left.received_both() && right.received_both()) {
343 const bool left_image_valid = left.is_valid();
344 const bool right_image_valid = right.is_valid();
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700345
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400346 auto new_vision_status = vision_status.MakeMessage();
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700347 new_vision_status->left_image_valid = left_image_valid;
348 new_vision_status->right_image_valid = right_image_valid;
349 if (left_image_valid && right_image_valid) {
Austin Schuh11945742016-04-13 22:18:36 -0700350 ::aos::vision::Vector<2> center_left(0.0, 0.0);
351 ::aos::vision::Vector<2> center_right(0.0, 0.0);
Austin Schuh6bf73052016-04-20 20:20:25 -0700352 double angle_left;
353 double angle_right;
Austin Schuh11945742016-04-13 22:18:36 -0700354 SelectTargets(left.target(), right.target(), &center_left,
Austin Schuh6bf73052016-04-20 20:20:25 -0700355 &center_right, &angle_left, &angle_right);
Austin Schuh11945742016-04-13 22:18:36 -0700356
357 // TODO(Ben): Remember this from last time instead of recalculating it
358 // each time.
359 ::aos::vision::Vector<2> last_center_left(0.0, 0.0);
360 ::aos::vision::Vector<2> last_center_right(0.0, 0.0);
Austin Schuh6bf73052016-04-20 20:20:25 -0700361 double last_angle_left;
362 double last_angle_right;
Austin Schuh11945742016-04-13 22:18:36 -0700363 SelectTargets(left.last_target(), right.last_target(),
Parker Schuh2cd173d2017-01-28 00:12:01 -0800364 &last_center_left, &last_center_right, &last_angle_left,
365 &last_angle_right);
Austin Schuh11945742016-04-13 22:18:36 -0700366
367 ::aos::vision::Vector<2> filtered_center_left(0.0, 0.0);
368 ::aos::vision::Vector<2> filtered_center_right(0.0, 0.0);
Austin Schuh6bf73052016-04-20 20:20:25 -0700369 double filtered_angle_left;
370 double filtered_angle_right;
Austin Schuh11945742016-04-13 22:18:36 -0700371 if (left.capture_time() < right.capture_time()) {
372 filtered_center_left = center_left;
Austin Schuh6bf73052016-04-20 20:20:25 -0700373 filtered_angle_left = angle_left;
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800374 new_vision_status->target_time =
375 chrono::duration_cast<chrono::nanoseconds>(
Parker Schuh2cd173d2017-01-28 00:12:01 -0800376 left.capture_time().time_since_epoch())
377 .count();
Austin Schuh6bf73052016-04-20 20:20:25 -0700378 CalculateFiltered(left, right, center_right, last_center_right,
379 angle_right, last_angle_right,
380 &filtered_center_right, &filtered_angle_right);
Austin Schuh11945742016-04-13 22:18:36 -0700381 } else {
382 filtered_center_right = center_right;
Austin Schuh6bf73052016-04-20 20:20:25 -0700383 filtered_angle_right = angle_right;
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800384 new_vision_status->target_time =
385 chrono::duration_cast<chrono::nanoseconds>(
Parker Schuh2cd173d2017-01-28 00:12:01 -0800386 right.capture_time().time_since_epoch())
387 .count();
Austin Schuh6bf73052016-04-20 20:20:25 -0700388 CalculateFiltered(right, left, center_left, last_center_left,
389 angle_left, last_angle_left, &filtered_center_left,
390 &filtered_angle_left);
Austin Schuh11945742016-04-13 22:18:36 -0700391 }
392
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700393 double distance, horizontal_angle, vertical_angle;
Austin Schuh11945742016-04-13 22:18:36 -0700394 stereo.Process(filtered_center_left, filtered_center_right, &distance,
395 &horizontal_angle, &vertical_angle);
396 new_vision_status->left_image_timestamp =
397 left.target().image_timestamp();
398 new_vision_status->right_image_timestamp =
399 right.target().image_timestamp();
400 new_vision_status->left_send_timestamp = left.target().send_timestamp();
Parker Schuh2cd173d2017-01-28 00:12:01 -0800401 new_vision_status->right_send_timestamp =
402 right.target().send_timestamp();
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700403 new_vision_status->horizontal_angle = horizontal_angle;
404 new_vision_status->vertical_angle = vertical_angle;
405 new_vision_status->distance = distance;
Austin Schuh6bf73052016-04-20 20:20:25 -0700406 new_vision_status->angle =
407 (filtered_angle_left + filtered_angle_right) / 2.0;
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700408 }
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400409
Brian Silvermanbc831182016-04-16 02:06:09 -0400410 if (drivetrain_offset.CompleteVisionStatus(new_vision_status.get())) {
411 LOG_STRUCT(DEBUG, "vision", *new_vision_status);
412 if (!new_vision_status.Send()) {
413 LOG(ERROR, "Failed to send vision information\n");
414 }
415 } else {
416 LOG_STRUCT(WARNING, "vision without drivetrain", *new_vision_status);
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400417 }
418 }
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700419
420 if (target.camera_index() == 0) {
Austin Schuh11945742016-04-13 22:18:36 -0700421 LOG(DEBUG, "left_target: %s\n", left.target().ShortDebugString().c_str());
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700422 } else {
Austin Schuh11945742016-04-13 22:18:36 -0700423 LOG(DEBUG, "right_target: %s\n",
424 right.target().ShortDebugString().c_str());
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700425 }
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400426 }
Brian Silvermanbc831182016-04-16 02:06:09 -0400427
428 drivetrain_offset.Quit();
429 drivetrain_offset_thread.join();
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400430}
431
432} // namespace vision
433} // namespace y2016
434
435int main(int /*argc*/, char ** /*argv*/) {
436 ::aos::InitNRT();
437 ::y2016::vision::Main();
438}