blob: 7ade8e7162e5ddc919f086a9bb019067741ac75c [file] [log] [blame]
Brian Silverman2ccf8c52016-03-15 00:22:26 -04001#include <stdlib.h>
2#include <netdb.h>
3#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
13#include "aos/linux_code/init.h"
14#include "aos/common/time.h"
15#include "aos/common/logging/logging.h"
16#include "aos/common/logging/queue_logging.h"
17#include "aos/vision/events/udp.h"
Brian Silvermanbc831182016-04-16 02:06:09 -040018#include "aos/common/mutex.h"
19
20#include "frc971/control_loops/drivetrain/drivetrain.q.h"
Brian Silverman2ccf8c52016-03-15 00:22:26 -040021
22#include "y2016/vision/vision.q.h"
23#include "y2016/vision/vision_data.pb.h"
24#include "y2016/vision/stereo_geometry.h"
25#include "y2016/constants.h"
26
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) {
Austin Schuh11945742016-04-13 22:18:36 -0700182 const double age_ratio =
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800183 chrono::duration_cast<chrono::duration<double>>(
184 older.capture_time() - newer.last_capture_time()).count() /
185 chrono::duration_cast<chrono::duration<double>>(
186 newer.capture_time() - newer.last_capture_time()).count();
Austin Schuh6bf73052016-04-20 20:20:25 -0700187 interpolated_result->Set(
Austin Schuh11945742016-04-13 22:18:36 -0700188 newer_center.x() * age_ratio + (1 - age_ratio) * last_newer_center.x(),
189 newer_center.y() * age_ratio + (1 - age_ratio) * last_newer_center.y());
Austin Schuh6bf73052016-04-20 20:20:25 -0700190
191 *interpolated_angle = angle * age_ratio + (1 - age_ratio) * last_angle;
Austin Schuh11945742016-04-13 22:18:36 -0700192}
ben54dbccb2016-03-20 14:42:28 -0700193
Brian Silvermanbc831182016-04-16 02:06:09 -0400194// Handles calculating drivetrain offsets.
195class DrivetrainOffsetCalculator {
196 public:
197 // To be called by ::std::thread.
198 void operator()() {
199 auto &status = ::frc971::control_loops::drivetrain_queue.status;
200 while (run_) {
201 status.FetchAnother();
202
203 ::aos::MutexLocker locker(&lock_);
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800204 data_[data_index_].time = status->sent_time;
Brian Silvermanbc831182016-04-16 02:06:09 -0400205 data_[data_index_].left = status->estimated_left_position;
206 data_[data_index_].right = status->estimated_right_position;
207 ++data_index_;
208 if (data_index_ == data_.size()) data_index_ = 0;
209 if (valid_data_ < data_.size()) ++valid_data_;
210 }
211 }
212
213 // Takes a vision status message with everything except
214 // drivetrain_{left,right}_position set and sets those.
215 // Returns false if it doesn't have enough data to fill them out.
216 bool CompleteVisionStatus(::y2016::vision::VisionStatus *status) {
217 if (valid_data_ == 0) return false;
218
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800219 const monotonic_clock::time_point capture_time =
220 monotonic_clock::time_point(chrono::nanoseconds(status->target_time));
Brian Silvermanbc831182016-04-16 02:06:09 -0400221 DrivetrainData before, after;
222 FindBeforeAfter(&before, &after, capture_time);
223
224 if (before.time == after.time) {
225 status->drivetrain_left_position = before.left;
226 status->drivetrain_right_position = before.right;
227 } else {
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800228 const double age_ratio = chrono::duration_cast<chrono::duration<double>>(
229 capture_time - before.time).count() /
230 chrono::duration_cast<chrono::duration<double>>(
231 after.time - before.time).count();
Brian Silvermanbc831182016-04-16 02:06:09 -0400232 status->drivetrain_left_position =
233 before.left * (1 - age_ratio) + after.left * age_ratio;
234 status->drivetrain_right_position =
235 before.right * (1 - age_ratio) + after.right * age_ratio;
236 }
237
238 return true;
239 }
240
241 void Quit() { run_ = false; }
242
243 private:
244 struct DrivetrainData {
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800245 monotonic_clock::time_point time;
Brian Silvermanbc831182016-04-16 02:06:09 -0400246 double left, right;
247 };
248
249 // Fills out before and after with the data surrounding capture_time.
250 // They might be identical if that's the closest approximation.
251 // Do not call this if valid_data_ is 0.
252 void FindBeforeAfter(DrivetrainData *before, DrivetrainData *after,
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800253 monotonic_clock::time_point capture_time) {
Brian Silvermanbc831182016-04-16 02:06:09 -0400254 ::aos::MutexLocker locker(&lock_);
255 size_t location = 0;
256 while (true) {
257 // We hit the end of our data. Just fill them both out as the last data
258 // point.
259 if (location >= valid_data_) {
260 *before = *after =
261 data_[previous_index((valid_data_ + data_index_) % data_.size())];
262 return;
263 }
264
265 // The index into data_ corresponding to location positions after
266 // (data_index_ - 1).
267 const size_t index = previous_index(location + data_index_);
268
269 // If we've found the one we want.
270 if (data_[index].time > capture_time) {
271 *after = data_[index];
272 if (location == 0) {
273 // If this is the first one and it's already after, just return the
274 // same thing for both.
275 *before = data_[index];
276 } else {
277 *before = data_[previous_index(index)];
278 }
279 return;
280 }
281
282 ++location;
283 }
284 }
285
286 size_t previous_index(size_t index) const {
287 if (index == 0) {
288 return data_.size() - 1;
289 } else {
290 return index - 1;
291 }
292 }
293
294 ::std::array<DrivetrainData, 200> data_;
295 // The index into data_ the next data point is going at.
296 size_t data_index_ = 0;
297 // How many elemets of data_ are valid.
298 size_t valid_data_ = 0;
299
300 ::aos::Mutex lock_;
301
302 ::std::atomic<bool> run_{true};
303};
304
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400305void Main() {
306 StereoGeometry stereo(constants::GetValues().vision_name);
307 LOG(INFO, "calibration: %s\n",
308 stereo.calibration().ShortDebugString().c_str());
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400309
Brian Silvermanbc831182016-04-16 02:06:09 -0400310 DrivetrainOffsetCalculator drivetrain_offset;
311 ::std::thread drivetrain_offset_thread(::std::ref(drivetrain_offset));
312
Austin Schuh11945742016-04-13 22:18:36 -0700313 CameraHandler left;
314 CameraHandler right;
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700315
316 ::aos::vision::RXUdpSocket recv(8080);
317 char rawData[65507];
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700318
319 while (true) {
320 // TODO(austin): Don't malloc.
321 VisionData target;
322 int size = recv.Recv(rawData, 65507);
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800323 monotonic_clock::time_point now = monotonic_clock::now();
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700324
325 if (target.ParseFromArray(rawData, size)) {
326 if (target.camera_index() == 0) {
Austin Schuh11945742016-04-13 22:18:36 -0700327 left.Received(target, now);
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700328 } else {
Austin Schuh11945742016-04-13 22:18:36 -0700329 right.Received(target, now);
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400330 }
331 } else {
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700332 LOG(ERROR, "oh noes: parse error\n");
333 continue;
334 }
335
Austin Schuh11945742016-04-13 22:18:36 -0700336 left.CheckStale(now);
337 right.CheckStale(now);
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400338
Austin Schuh11945742016-04-13 22:18:36 -0700339 if (left.received_both() && right.received_both()) {
340 const bool left_image_valid = left.is_valid();
341 const bool right_image_valid = right.is_valid();
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700342
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400343 auto new_vision_status = vision_status.MakeMessage();
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700344 new_vision_status->left_image_valid = left_image_valid;
345 new_vision_status->right_image_valid = right_image_valid;
346 if (left_image_valid && right_image_valid) {
Austin Schuh11945742016-04-13 22:18:36 -0700347 ::aos::vision::Vector<2> center_left(0.0, 0.0);
348 ::aos::vision::Vector<2> center_right(0.0, 0.0);
Austin Schuh6bf73052016-04-20 20:20:25 -0700349 double angle_left;
350 double angle_right;
Austin Schuh11945742016-04-13 22:18:36 -0700351 SelectTargets(left.target(), right.target(), &center_left,
Austin Schuh6bf73052016-04-20 20:20:25 -0700352 &center_right, &angle_left, &angle_right);
Austin Schuh11945742016-04-13 22:18:36 -0700353
354 // TODO(Ben): Remember this from last time instead of recalculating it
355 // each time.
356 ::aos::vision::Vector<2> last_center_left(0.0, 0.0);
357 ::aos::vision::Vector<2> last_center_right(0.0, 0.0);
Austin Schuh6bf73052016-04-20 20:20:25 -0700358 double last_angle_left;
359 double last_angle_right;
Austin Schuh11945742016-04-13 22:18:36 -0700360 SelectTargets(left.last_target(), right.last_target(),
Austin Schuh6bf73052016-04-20 20:20:25 -0700361 &last_center_left, &last_center_right,
362 &last_angle_left, &last_angle_right);
Austin Schuh11945742016-04-13 22:18:36 -0700363
364 ::aos::vision::Vector<2> filtered_center_left(0.0, 0.0);
365 ::aos::vision::Vector<2> filtered_center_right(0.0, 0.0);
Austin Schuh6bf73052016-04-20 20:20:25 -0700366 double filtered_angle_left;
367 double filtered_angle_right;
Austin Schuh11945742016-04-13 22:18:36 -0700368 if (left.capture_time() < right.capture_time()) {
369 filtered_center_left = center_left;
Austin Schuh6bf73052016-04-20 20:20:25 -0700370 filtered_angle_left = angle_left;
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800371 new_vision_status->target_time =
372 chrono::duration_cast<chrono::nanoseconds>(
373 left.capture_time().time_since_epoch()).count();
Austin Schuh6bf73052016-04-20 20:20:25 -0700374 CalculateFiltered(left, right, center_right, last_center_right,
375 angle_right, last_angle_right,
376 &filtered_center_right, &filtered_angle_right);
Austin Schuh11945742016-04-13 22:18:36 -0700377 } else {
378 filtered_center_right = center_right;
Austin Schuh6bf73052016-04-20 20:20:25 -0700379 filtered_angle_right = angle_right;
Austin Schuhfb5f7de2016-11-26 15:15:19 -0800380 new_vision_status->target_time =
381 chrono::duration_cast<chrono::nanoseconds>(
382 right.capture_time().time_since_epoch()).count();
Austin Schuh6bf73052016-04-20 20:20:25 -0700383 CalculateFiltered(right, left, center_left, last_center_left,
384 angle_left, last_angle_left, &filtered_center_left,
385 &filtered_angle_left);
Austin Schuh11945742016-04-13 22:18:36 -0700386 }
387
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700388 double distance, horizontal_angle, vertical_angle;
Austin Schuh11945742016-04-13 22:18:36 -0700389 stereo.Process(filtered_center_left, filtered_center_right, &distance,
390 &horizontal_angle, &vertical_angle);
391 new_vision_status->left_image_timestamp =
392 left.target().image_timestamp();
393 new_vision_status->right_image_timestamp =
394 right.target().image_timestamp();
395 new_vision_status->left_send_timestamp = left.target().send_timestamp();
396 new_vision_status->right_send_timestamp = right.target().send_timestamp();
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700397 new_vision_status->horizontal_angle = horizontal_angle;
398 new_vision_status->vertical_angle = vertical_angle;
399 new_vision_status->distance = distance;
Austin Schuh6bf73052016-04-20 20:20:25 -0700400 new_vision_status->angle =
401 (filtered_angle_left + filtered_angle_right) / 2.0;
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700402 }
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400403
Brian Silvermanbc831182016-04-16 02:06:09 -0400404 if (drivetrain_offset.CompleteVisionStatus(new_vision_status.get())) {
405 LOG_STRUCT(DEBUG, "vision", *new_vision_status);
406 if (!new_vision_status.Send()) {
407 LOG(ERROR, "Failed to send vision information\n");
408 }
409 } else {
410 LOG_STRUCT(WARNING, "vision without drivetrain", *new_vision_status);
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400411 }
412 }
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700413
414 if (target.camera_index() == 0) {
Austin Schuh11945742016-04-13 22:18:36 -0700415 LOG(DEBUG, "left_target: %s\n", left.target().ShortDebugString().c_str());
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700416 } else {
Austin Schuh11945742016-04-13 22:18:36 -0700417 LOG(DEBUG, "right_target: %s\n",
418 right.target().ShortDebugString().c_str());
Austin Schuhc65b0ea2016-03-16 22:09:19 -0700419 }
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400420 }
Brian Silvermanbc831182016-04-16 02:06:09 -0400421
422 drivetrain_offset.Quit();
423 drivetrain_offset_thread.join();
Brian Silverman2ccf8c52016-03-15 00:22:26 -0400424}
425
426} // namespace vision
427} // namespace y2016
428
429int main(int /*argc*/, char ** /*argv*/) {
430 ::aos::InitNRT();
431 ::y2016::vision::Main();
432}