blob: 291a164aae0d0f355c4cfb41950dbc10a2a9a4ba [file] [log] [blame]
Austin Schuh010eb812014-10-25 18:06:49 -07001#include <stdio.h>
2#include <string.h>
3#include <thread>
4#include <mutex>
5#include <unistd.h>
6#include <inttypes.h>
7
8#include "aos/prime/output/motor_output.h"
9#include "aos/common/controls/output_check.q.h"
10#include "aos/common/controls/sensor_generation.q.h"
11#include "aos/common/logging/logging.h"
12#include "aos/common/logging/queue_logging.h"
13#include "aos/common/messages/robot_state.q.h"
14#include "aos/common/time.h"
15#include "aos/common/util/log_interval.h"
16#include "aos/common/util/phased_loop.h"
17#include "aos/common/util/wrapping_counter.h"
18#include "aos/common/network/team_number.h"
19#include "aos/linux_code/init.h"
20
21#include "frc971/control_loops/drivetrain/drivetrain.q.h"
22#include "frc971/control_loops/claw/claw.q.h"
23#include "frc971/control_loops/shooter/shooter.q.h"
24#include "frc971/constants.h"
25#include "frc971/queues/other_sensors.q.h"
26#include "frc971/queues/to_log.q.h"
27
28#include <WPILib.h>
29
30#ifndef M_PI
31#define M_PI 3.14159265358979323846
32#endif
33
34using ::aos::util::SimpleLogInterval;
35using ::frc971::control_loops::drivetrain;
36using ::frc971::sensors::other_sensors;
37using ::frc971::sensors::gyro_reading;
38using ::aos::util::WrappingCounter;
39
40namespace frc971 {
41namespace output {
42
43void SetThreadRealtimePriority(int priority) {
44 struct sched_param param;
45 param.sched_priority = priority;
46 if (sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
47 PLOG(FATAL, "sched_setscheduler failed");
48 }
49}
50
51class priority_mutex {
52 public:
53 typedef pthread_mutex_t *native_handle_type;
54
55 // TODO(austin): Write a test case for the mutex, and make the constructor
56 // constexpr.
57 priority_mutex() {
58 pthread_mutexattr_t attr;
Austin Schuh010eb812014-10-25 18:06:49 -070059#ifdef NDEBUG
60#error "Won't let perror be no-op ed"
61#endif
Austin Schuhdb516032014-12-28 00:12:38 -080062 // Turn on priority inheritance.
Austin Schuh010eb812014-10-25 18:06:49 -070063 assert_perror(pthread_mutexattr_init(&attr));
64 assert_perror(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
65 assert_perror(pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT));
66
67 assert_perror(pthread_mutex_init(native_handle(), &attr));
68
69 assert_perror(pthread_mutexattr_destroy(&attr));
70 }
71
72 ~priority_mutex() { pthread_mutex_destroy(&handle_); }
73
74 void lock() { assert_perror(pthread_mutex_lock(&handle_)); }
75 bool try_lock() {
76 int ret = pthread_mutex_trylock(&handle_);
77 if (ret == 0) {
78 return true;
79 } else if (ret == EBUSY) {
80 return false;
81 } else {
82 assert_perror(ret);
83 }
84 }
85 void unlock() { assert_perror(pthread_mutex_unlock(&handle_)); }
86
87 native_handle_type native_handle() { return &handle_; }
88
89 private:
90 DISALLOW_COPY_AND_ASSIGN(priority_mutex);
91 pthread_mutex_t handle_;
92};
93
94class HallEffect : public DigitalInput {
95 public:
96 HallEffect(int index) : DigitalInput(index) {}
97 bool GetHall() { return !Get(); }
98};
99
100class EdgeCounter {
101 public:
102 EdgeCounter(int priority, Encoder *encoder, HallEffect *input,
103 priority_mutex *mutex)
104 : priority_(priority),
105 encoder_(encoder),
106 input_(input),
107 mutex_(mutex),
108 run_(true),
109 any_interrupt_count_(0) {
110 thread_.reset(new ::std::thread(::std::ref(*this)));
111 }
112
113 // Waits for interrupts, locks the mutex, and updates the internal state.
114 // Updates the any_interrupt_count count when the interrupt comes in without
115 // the lock.
Austin Schuhdb516032014-12-28 00:12:38 -0800116 void operator()() {
Austin Schuh010eb812014-10-25 18:06:49 -0700117 SetThreadRealtimePriority(priority_);
118
119 input_->RequestInterrupts();
120 input_->SetUpSourceEdge(true, true);
121
122 {
123 ::std::unique_lock<priority_mutex> mutex_guard(*mutex_);
124 current_value_ = input_->GetHall();
125 }
126
127 InterruptableSensorBase::WaitResult result = InterruptableSensorBase::kBoth;
128 while (run_) {
129 result = input_->WaitForInterrupt(
130 0.1, result != InterruptableSensorBase::kTimeout);
131 if (result == InterruptableSensorBase::kTimeout) {
132 continue;
133 }
134 ++any_interrupt_count_;
135
136 ::std::unique_lock<priority_mutex> mutex_guard(*mutex_);
137 int32_t encoder_value = encoder_->GetRaw();
138 bool hall_value = input_->GetHall();
139 if (current_value_ != hall_value) {
140 if (hall_value) {
141 ++positive_interrupt_count_;
142 last_positive_encoder_value_ = encoder_value;
143 } else {
144 ++negative_interrupt_count_;
145 last_negative_encoder_value_ = encoder_value;
146 }
147 } else {
148 LOG(WARNING, "Detected spurious edge on %d. Dropping it.\n",
149 input_->GetChannel());
150 }
151
152 current_value_ = hall_value;
153 }
154 }
155
156 // Updates the internal hall effect value given this new observation.
157 // The mutex provided at construction time must be held during this operation.
158 void set_polled_value(bool value) {
159 polled_value_ = value;
160 bool miss_match = (value != current_value_);
161 if (miss_match && last_miss_match_) {
162 current_value_ = value;
163 last_miss_match_ = false;
164 } else {
165 last_miss_match_ = miss_match;
166 }
167 }
168
169 // Signals the thread to quit next time it gets an interrupt.
170 void Quit() {
171 run_ = false;
172 thread_->join();
173 }
174
175 // Returns the total number of interrupts since construction time. This
176 // should be done without the mutex held.
177 int any_interrupt_count() const { return any_interrupt_count_; }
178 // Returns the current interrupt edge counts and encoder values.
179 // The mutex provided at construction time must be held during this operation.
180 int positive_interrupt_count() const { return positive_interrupt_count_; }
181 int negative_interrupt_count() const { return negative_interrupt_count_; }
182 int32_t last_positive_encoder_value() const {
183 return last_positive_encoder_value_;
184 }
185 int32_t last_negative_encoder_value() const {
186 return last_negative_encoder_value_;
187 }
188 // Returns the current polled value.
189 bool polled_value() const { return polled_value_; }
190
191 private:
192 int priority_;
193 Encoder *encoder_;
194 HallEffect *input_;
195 priority_mutex *mutex_;
196 ::std::atomic<bool> run_;
197
198 ::std::atomic<int> any_interrupt_count_;
199
200 // The following variables represent the current state. They must be
201 // synchronized by mutex_;
202 bool current_value_ = false;
203 bool polled_value_ = false;
204 bool last_miss_match_ = true;
205 int positive_interrupt_count_ = 0;
206 int negative_interrupt_count_ = 0;
207 int32_t last_positive_encoder_value_ = 0;
208 int32_t last_negative_encoder_value_ = 0;
209
210 ::std::unique_ptr<::std::thread> thread_;
211};
212
213// This class will synchronize sampling edges on a bunch of DigitalInputs with
214// the periodic poll.
215//
216// The data is provided to subclasses by calling SaveState when the state is
217// consistent and ready.
218template <int num_sensors>
219class PeriodicHallSynchronizer {
220 public:
221 PeriodicHallSynchronizer(
222 const char *name, int priority, int interrupt_priority,
223 ::std::unique_ptr<Encoder> encoder,
224 ::std::array<::std::unique_ptr<HallEffect>, num_sensors> *sensors)
225 : name_(name),
226 priority_(priority),
227 encoder_(::std::move(encoder)),
228 run_(true) {
229 for (int i = 0; i < num_sensors; ++i) {
230 sensors_[i] = ::std::move((*sensors)[i]);
231 edge_counters_[i] = ::std::unique_ptr<EdgeCounter>(new EdgeCounter(
232 interrupt_priority, encoder_.get(), sensors_[i].get(), &mutex_));
233 }
234 }
235
236 const char *name() const { return name_.c_str(); }
237
238 void StartThread() { thread_.reset(new ::std::thread(::std::ref(*this))); }
239
240 // Called when the state is consistent and up to date.
241 virtual void SaveState() = 0;
242
243 // Starts a sampling iteration. See RunIteration for usage.
244 void StartIteration() {
245 // Start by capturing the current interrupt counts.
246 for (int i = 0; i < num_sensors; ++i) {
247 interrupt_counts_[i] = edge_counters_[i]->any_interrupt_count();
248 }
249
250 {
251 // Now, update the encoder and sensor values.
252 ::std::unique_lock<priority_mutex> mutex_guard(mutex_);
253 encoder_value_ = encoder_->GetRaw();
254 for (int i = 0; i < num_sensors; ++i) {
255 edge_counters_[i]->set_polled_value(sensors_[i]->GetHall());
256 }
257 }
258 }
259
260 // Attempts to finish a sampling iteration. See RunIteration for usage.
261 // Returns true if the iteration succeeded, and false otherwise.
262 bool TryFinishingIteration() {
263 // Make sure no interrupts have occurred while we were waiting. If they
264 // have, we are in an inconsistent state and need to try again.
265 ::std::unique_lock<priority_mutex> mutex_guard(mutex_);
266 bool retry = false;
267 for (int i = 0; i < num_sensors; ++i) {
268 retry = retry || (interrupt_counts_[i] !=
269 edge_counters_[i]->any_interrupt_count());
270 }
271 if (!retry) {
272 SaveState();
273 return true;
274 }
275 LOG(WARNING, "Got an interrupt while sampling encoder %s, retrying\n",
276 name());
277 return false;
278 }
279
280 void RunIteration() {
281 while (true) {
282 StartIteration();
283
284 // Wait more than the amount of time it takes for a digital input change
285 // to go from visible to software to having triggered an interrupt.
286 ::aos::time::SleepFor(::aos::time::Time::InUS(120));
287
288 if (TryFinishingIteration()) {
289 return;
290 }
291 }
292 }
293
294 void operator()() {
295 SetThreadRealtimePriority(priority_);
296 while (run_) {
297 ::aos::time::PhasedLoopXMS(10, 9000);
298 RunIteration();
299 }
300 }
301
302 void Quit() {
303 run_ = false;
304 for (int i = 0; i < num_sensors; ++i) {
305 edge_counters_[i]->Quit();
306 }
307 if (thread_) {
308 thread_->join();
309 }
310 }
311
312 protected:
313 // These values are only safe to fetch from inside SaveState()
314 int32_t encoder_value() const { return encoder_value_; }
315 ::std::array<::std::unique_ptr<EdgeCounter>, num_sensors> &edge_counters() {
316 return edge_counters_;
317 }
318
319 private:
320 // A descriptive name for error messages.
321 ::std::string name_;
322 // The priority of the polling thread.
323 int priority_;
324 // The Encoder to sample.
325 ::std::unique_ptr<Encoder> encoder_;
326 // A list of all the digital inputs.
327 ::std::array<::std::unique_ptr<HallEffect>, num_sensors> sensors_;
328 // The mutex used to synchronize all the state.
329 priority_mutex mutex_;
330 ::std::atomic<bool> run_;
331
332 // The state.
333 // The current encoder value.
334 int32_t encoder_value_ = 0;
335 // The current edge counters.
336 ::std::array<::std::unique_ptr<EdgeCounter>, num_sensors> edge_counters_;
337
338 ::std::unique_ptr<::std::thread> thread_;
339 ::std::array<int, num_sensors> interrupt_counts_;
340};
341
342double drivetrain_translate(int32_t in) {
Austin Schuhdb516032014-12-28 00:12:38 -0800343 return static_cast<double>(in) /
344 (256.0 /*cpr*/ * 2.0 /*2x. Stupid WPILib*/) *
345 (18.0 / 50.0 /*output stage*/) * (56.0 / 30.0 /*encoder gears*/)
346 // * constants::GetValues().drivetrain_encoder_ratio
347 *
348 (3.5 /*wheel diameter*/ * 2.54 / 100.0 * M_PI);
Austin Schuh010eb812014-10-25 18:06:49 -0700349}
350
351static const double kVcc = 5.15;
352
353double gyro_translate(int64_t in) {
354 return in / 16.0 / 1000.0 / (180.0 / M_PI);
355}
356
357float hall_translate(const constants::ShifterHallEffect &k, float in_low,
358 float in_high) {
359 const float low_ratio =
360 0.5 * (in_low - static_cast<float>(k.low_gear_low)) /
361 static_cast<float>(k.low_gear_middle - k.low_gear_low);
362 const float high_ratio =
363 0.5 + 0.5 * (in_high - static_cast<float>(k.high_gear_middle)) /
364 static_cast<float>(k.high_gear_high - k.high_gear_middle);
365
366 // Return low when we are below 1/2, and high when we are above 1/2.
367 if (low_ratio + high_ratio < 1.0) {
368 return low_ratio;
369 } else {
370 return high_ratio;
371 }
372}
373
374double claw_translate(int32_t in) {
Austin Schuhdb516032014-12-28 00:12:38 -0800375 return static_cast<double>(in) / (256.0 /*cpr*/ * 4.0 /*quad*/) /
376 (18.0 / 48.0 /*encoder gears*/) / (12.0 / 60.0 /*chain reduction*/) *
377 (M_PI / 180.0) *
378 2.0 /*TODO(austin): Debug this, encoders read too little*/;
Austin Schuh010eb812014-10-25 18:06:49 -0700379}
380
381double shooter_translate(int32_t in) {
Austin Schuhdb516032014-12-28 00:12:38 -0800382 return static_cast<double>(in) / (256.0 /*cpr*/ * 4.0 /*quad*/) *
383 16 /*sprocket teeth*/ * 0.375 /*chain pitch*/
384 * (2.54 / 100.0 /*in to m*/);
Austin Schuh010eb812014-10-25 18:06:49 -0700385}
386
Austin Schuh010eb812014-10-25 18:06:49 -0700387// This class sends out half of the claw position state at 100 hz.
388class HalfClawHallSynchronizer : public PeriodicHallSynchronizer<3> {
389 public:
390 // Constructs a HalfClawHallSynchronizer.
391 //
392 // priority is the priority of the polling thread.
393 // interrupt_priority is the priority of the interrupt threads.
394 // encoder is the encoder to read.
395 // sensors is an array of hall effect sensors. The sensors[0] is the front
Austin Schuhdb516032014-12-28 00:12:38 -0800396 // sensor, sensors[1] is the calibration sensor, sensors[2] is the back
397 // sensor.
Austin Schuh010eb812014-10-25 18:06:49 -0700398 HalfClawHallSynchronizer(
399 const char *name, int priority, int interrupt_priority,
400 ::std::unique_ptr<Encoder> encoder,
401 ::std::array<::std::unique_ptr<HallEffect>, 3> *sensors, bool reversed)
402 : PeriodicHallSynchronizer<3>(name, priority, interrupt_priority,
403 ::std::move(encoder), sensors),
404 reversed_(reversed) {}
405
406 void set_position(control_loops::HalfClawPosition *half_claw_position) {
407 half_claw_position_ = half_claw_position;
408 }
409
410 // Saves the state so that it can be sent if it was synchronized.
411 virtual void SaveState() {
412 const auto &front = edge_counters()[0];
413 half_claw_position_->front.current = front->polled_value();
414 half_claw_position_->front.posedge_count =
415 front->positive_interrupt_count();
416 half_claw_position_->front.negedge_count =
417 front->negative_interrupt_count();
418
419 const auto &calibration = edge_counters()[1];
420 half_claw_position_->calibration.current = calibration->polled_value();
421 half_claw_position_->calibration.posedge_count =
422 calibration->positive_interrupt_count();
423 half_claw_position_->calibration.negedge_count =
424 calibration->negative_interrupt_count();
425
426 const auto &back = edge_counters()[2];
427 half_claw_position_->back.current = back->polled_value();
428 half_claw_position_->back.posedge_count = back->positive_interrupt_count();
429 half_claw_position_->back.negedge_count = back->negative_interrupt_count();
430
431 const double multiplier = reversed_ ? -1.0 : 1.0;
432
433 half_claw_position_->position =
434 multiplier * claw_translate(encoder_value());
435
436 // We assume here that we can only have 1 sensor have a posedge per cycle.
437 {
438 half_claw_position_->posedge_value =
439 last_half_claw_position_.posedge_value;
440 int posedge_changes = 0;
441 if (half_claw_position_->front.posedge_count !=
442 last_half_claw_position_.front.posedge_count) {
443 ++posedge_changes;
444 half_claw_position_->posedge_value =
445 multiplier * claw_translate(front->last_positive_encoder_value());
446 LOG(INFO, "Got a front posedge\n");
447 }
448
449 if (half_claw_position_->back.posedge_count !=
450 last_half_claw_position_.back.posedge_count) {
451 ++posedge_changes;
452 half_claw_position_->posedge_value =
453 multiplier * claw_translate(back->last_positive_encoder_value());
454 LOG(INFO, "Got a back posedge\n");
455 }
456
457 if (half_claw_position_->calibration.posedge_count !=
458 last_half_claw_position_.calibration.posedge_count) {
459 ++posedge_changes;
460 half_claw_position_->posedge_value =
461 multiplier *
462 claw_translate(calibration->last_positive_encoder_value());
463 LOG(INFO, "Got a calibration posedge\n");
464 }
465
466 if (posedge_changes > 1) {
467 LOG(WARNING, "Found more than 1 positive edge on %s\n", name());
468 }
469 }
470
471 {
472 half_claw_position_->negedge_value =
473 last_half_claw_position_.negedge_value;
474 int negedge_changes = 0;
475 if (half_claw_position_->front.negedge_count !=
476 last_half_claw_position_.front.negedge_count) {
477 ++negedge_changes;
478 half_claw_position_->negedge_value =
479 multiplier * claw_translate(front->last_negative_encoder_value());
480 LOG(INFO, "Got a front negedge\n");
481 }
482
483 if (half_claw_position_->back.negedge_count !=
484 last_half_claw_position_.back.negedge_count) {
485 ++negedge_changes;
486 half_claw_position_->negedge_value =
487 multiplier * claw_translate(back->last_negative_encoder_value());
488 LOG(INFO, "Got a back negedge\n");
489 }
490
491 if (half_claw_position_->calibration.negedge_count !=
492 last_half_claw_position_.calibration.negedge_count) {
493 ++negedge_changes;
494 half_claw_position_->negedge_value =
495 multiplier *
496 claw_translate(calibration->last_negative_encoder_value());
497 LOG(INFO, "Got a calibration negedge\n");
498 }
499
500 if (negedge_changes > 1) {
501 LOG(WARNING, "Found more than 1 negative edge on %s\n", name());
502 }
503 }
504
505 last_half_claw_position_ = *half_claw_position_;
506 }
507
508 private:
509 control_loops::HalfClawPosition *half_claw_position_;
510 control_loops::HalfClawPosition last_half_claw_position_;
511 bool reversed_;
512};
513
Austin Schuh010eb812014-10-25 18:06:49 -0700514// This class sends out the shooter position state at 100 hz.
515class ShooterHallSynchronizer : public PeriodicHallSynchronizer<2> {
516 public:
517 // Constructs a ShooterHallSynchronizer.
518 //
519 // priority is the priority of the polling thread.
520 // interrupt_priority is the priority of the interrupt threads.
521 // encoder is the encoder to read.
522 // sensors is an array of hall effect sensors. The sensors[0] is the proximal
523 // sensor, sensors[1] is the distal sensor.
524 // shooter_plunger is the plunger.
525 // shooter_latch is the latch.
526 ShooterHallSynchronizer(
527 int priority, int interrupt_priority, ::std::unique_ptr<Encoder> encoder,
528 ::std::array<::std::unique_ptr<HallEffect>, 2> *sensors,
529 ::std::unique_ptr<HallEffect> shooter_plunger,
530 ::std::unique_ptr<HallEffect> shooter_latch)
531 : PeriodicHallSynchronizer<2>("shooter", priority, interrupt_priority,
532 ::std::move(encoder), sensors),
533 shooter_plunger_(::std::move(shooter_plunger)),
534 shooter_latch_(::std::move(shooter_latch)) {}
535
536 // Saves the state so that it can be sent if it was synchronized.
537 virtual void SaveState() {
538 auto shooter_position =
539 control_loops::shooter_queue_group.position.MakeMessage();
540
541 shooter_position->plunger = shooter_plunger_->GetHall();
542 shooter_position->latch = shooter_latch_->GetHall();
543 shooter_position->position = shooter_translate(encoder_value());
544
545 {
546 const auto &proximal_edge_counter = edge_counters()[0];
547 shooter_position->pusher_proximal.current =
548 proximal_edge_counter->polled_value();
549 shooter_position->pusher_proximal.posedge_count =
550 proximal_edge_counter->positive_interrupt_count();
551 shooter_position->pusher_proximal.negedge_count =
552 proximal_edge_counter->negative_interrupt_count();
553 shooter_position->pusher_proximal.posedge_value = shooter_translate(
554 proximal_edge_counter->last_positive_encoder_value());
555 }
556
557 {
Austin Schuhdb516032014-12-28 00:12:38 -0800558 const auto &distal_edge_counter = edge_counters()[1];
559 shooter_position->pusher_distal.current =
560 distal_edge_counter->polled_value();
561 shooter_position->pusher_distal.posedge_count =
562 distal_edge_counter->positive_interrupt_count();
563 shooter_position->pusher_distal.negedge_count =
564 distal_edge_counter->negative_interrupt_count();
565 shooter_position->pusher_distal.posedge_value =
566 shooter_translate(distal_edge_counter->last_positive_encoder_value());
Austin Schuh010eb812014-10-25 18:06:49 -0700567 }
568
569 shooter_position.Send();
570 }
571
572 private:
573 ::std::unique_ptr<HallEffect> shooter_plunger_;
574 ::std::unique_ptr<HallEffect> shooter_latch_;
575};
576
577
578class SensorReader {
579 public:
580 SensorReader()
581 : auto_selector_analog_(new AnalogInput(4)),
582 left_encoder_(new Encoder(10, 11, false, Encoder::k2X)), // E0
583 right_encoder_(new Encoder(12, 13, false, Encoder::k2X)), // E1
584 low_left_drive_hall_(new AnalogInput(2)),
585 high_left_drive_hall_(new AnalogInput(3)),
586 low_right_drive_hall_(new AnalogInput(1)),
587 high_right_drive_hall_(new AnalogInput(0)),
588 shooter_plunger_(new HallEffect(1)), // S3
589 shooter_latch_(new HallEffect(0)), // S4
590 shooter_distal_(new HallEffect(2)), // S2
591 shooter_proximal_(new HallEffect(3)), // S1
Austin Schuhdb516032014-12-28 00:12:38 -0800592 shooter_encoder_(new Encoder(15, 14)), // E2
Austin Schuh010eb812014-10-25 18:06:49 -0700593 claw_top_front_hall_(new HallEffect(5)), // R2
594 claw_top_calibration_hall_(new HallEffect(6)), // R3
595 claw_top_back_hall_(new HallEffect(4)), // R2
Austin Schuhdb516032014-12-28 00:12:38 -0800596 claw_top_encoder_(new Encoder(16, 17)), // E3
Austin Schuh010eb812014-10-25 18:06:49 -0700597 // L2 Middle Left hall effect sensor.
598 claw_bottom_front_hall_(new HallEffect(8)),
599 // L3 Bottom Left hall effect sensor
600 claw_bottom_calibration_hall_(new HallEffect(9)),
601 // L1 Top Left hall effect sensor
602 claw_bottom_back_hall_(new HallEffect(7)),
Austin Schuhdb516032014-12-28 00:12:38 -0800603 claw_bottom_encoder_(new Encoder(18, 19)), // E5
Austin Schuh010eb812014-10-25 18:06:49 -0700604 run_(true) {
605 filter_.SetPeriodNanoSeconds(100000);
606 filter_.Add(shooter_plunger_.get());
607 filter_.Add(shooter_latch_.get());
608 filter_.Add(shooter_distal_.get());
609 filter_.Add(shooter_proximal_.get());
610 filter_.Add(claw_top_front_hall_.get());
611 filter_.Add(claw_top_calibration_hall_.get());
612 filter_.Add(claw_top_back_hall_.get());
613 filter_.Add(claw_bottom_front_hall_.get());
614 filter_.Add(claw_bottom_calibration_hall_.get());
615 filter_.Add(claw_bottom_back_hall_.get());
616 printf("Filtering all hall effect sensors with a %" PRIu64
617 " nanosecond window\n",
618 filter_.GetPeriodNanoSeconds());
619 }
620
621 void operator()() {
622 const int kPriority = 30;
623 const int kInterruptPriority = 55;
624 SetThreadRealtimePriority(kPriority);
625
626 ::std::array<::std::unique_ptr<HallEffect>, 2> shooter_sensors;
627 shooter_sensors[0] = ::std::move(shooter_proximal_);
628 shooter_sensors[1] = ::std::move(shooter_distal_);
629 ShooterHallSynchronizer shooter(
630 kPriority, kInterruptPriority, ::std::move(shooter_encoder_),
631 &shooter_sensors, ::std::move(shooter_plunger_),
632 ::std::move(shooter_latch_));
633 shooter.StartThread();
634
635 ::std::array<::std::unique_ptr<HallEffect>, 3> claw_top_sensors;
636 claw_top_sensors[0] = ::std::move(claw_top_front_hall_);
637 claw_top_sensors[1] = ::std::move(claw_top_calibration_hall_);
638 claw_top_sensors[2] = ::std::move(claw_top_back_hall_);
639 HalfClawHallSynchronizer top_claw("top_claw", kPriority, kInterruptPriority,
640 ::std::move(claw_top_encoder_),
641 &claw_top_sensors, false);
642
643 ::std::array<::std::unique_ptr<HallEffect>, 3> claw_bottom_sensors;
644 claw_bottom_sensors[0] = ::std::move(claw_bottom_front_hall_);
645 claw_bottom_sensors[1] = ::std::move(claw_bottom_calibration_hall_);
646 claw_bottom_sensors[2] = ::std::move(claw_bottom_back_hall_);
647 HalfClawHallSynchronizer bottom_claw(
648 "bottom_claw", kPriority, kInterruptPriority,
649 ::std::move(claw_bottom_encoder_), &claw_bottom_sensors, true);
650
651 while (run_) {
652 ::aos::time::PhasedLoopXMS(10, 9000);
653 RunIteration();
654
655 auto claw_position =
656 control_loops::claw_queue_group.position.MakeMessage();
657 bottom_claw.set_position(&claw_position->bottom);
658 top_claw.set_position(&claw_position->top);
659 while (true) {
660 bottom_claw.StartIteration();
661 top_claw.StartIteration();
662
663 // Wait more than the amount of time it takes for a digital input change
664 // to go from visible to software to having triggered an interrupt.
665 ::aos::time::SleepFor(::aos::time::Time::InUS(120));
666
Austin Schuhdb516032014-12-28 00:12:38 -0800667 if (bottom_claw.TryFinishingIteration() &&
668 top_claw.TryFinishingIteration()) {
Austin Schuh010eb812014-10-25 18:06:49 -0700669 break;
670 }
671 }
672
673 claw_position.Send();
674 }
675 shooter.Quit();
676 top_claw.Quit();
677 bottom_claw.Quit();
678 }
679
680 void RunIteration() {
681 //::aos::time::TimeFreezer time_freezer;
682 DriverStation *ds = DriverStation::GetInstance();
683
684 bool bad_gyro = true;
685 // TODO(brians): Switch to LogInterval for these things.
686 /*
687 if (data->uninitialized_gyro) {
688 LOG(DEBUG, "uninitialized gyro\n");
689 bad_gyro = true;
690 } else if (data->zeroing_gyro) {
691 LOG(DEBUG, "zeroing gyro\n");
692 bad_gyro = true;
693 } else if (data->bad_gyro) {
694 LOG(ERROR, "bad gyro\n");
695 bad_gyro = true;
696 } else if (data->old_gyro_reading) {
697 LOG(WARNING, "old/bad gyro reading\n");
698 bad_gyro = true;
699 } else {
700 bad_gyro = false;
701 }
702 */
703
704 if (!bad_gyro) {
705 // TODO(austin): Read the gyro.
706 gyro_reading.MakeWithBuilder().angle(0).Send();
707 }
708
Austin Schuhdb516032014-12-28 00:12:38 -0800709 if (ds->IsSysActive()) {
Austin Schuh010eb812014-10-25 18:06:49 -0700710 auto message = ::aos::controls::output_check_received.MakeMessage();
711 // TODO(brians): Actually read a pulse value from the roboRIO.
712 message->pwm_value = 0;
713 message->pulse_length = -1;
714 LOG_STRUCT(DEBUG, "received", *message);
715 message.Send();
716 }
717
718 ::frc971::sensors::auto_mode.MakeWithBuilder()
719 .voltage(auto_selector_analog_->GetVoltage())
720 .Send();
721
722 // TODO(austin): Calibrate the shifter constants again.
723 drivetrain.position.MakeWithBuilder()
724 .right_encoder(drivetrain_translate(right_encoder_->GetRaw()))
725 .left_encoder(-drivetrain_translate(left_encoder_->GetRaw()))
726 .left_shifter_position(
727 hall_translate(constants::GetValues().left_drive,
728 low_left_drive_hall_->GetVoltage(),
729 high_left_drive_hall_->GetVoltage()))
730 .right_shifter_position(
731 hall_translate(constants::GetValues().right_drive,
732 low_right_drive_hall_->GetVoltage(),
733 high_right_drive_hall_->GetVoltage()))
734 .battery_voltage(ds->GetBatteryVoltage())
735 .Send();
736
737 // Signal that we are allive.
738 ::aos::controls::sensor_generation.MakeWithBuilder()
739 .reader_pid(getpid())
740 .cape_resets(0)
741 .Send();
742 }
743
744 void Quit() { run_ = false; }
745
746 private:
747 ::std::unique_ptr<AnalogInput> auto_selector_analog_;
748
749 ::std::unique_ptr<Encoder> left_encoder_;
750 ::std::unique_ptr<Encoder> right_encoder_;
751 ::std::unique_ptr<AnalogInput> low_left_drive_hall_;
752 ::std::unique_ptr<AnalogInput> high_left_drive_hall_;
753 ::std::unique_ptr<AnalogInput> low_right_drive_hall_;
754 ::std::unique_ptr<AnalogInput> high_right_drive_hall_;
755
756 ::std::unique_ptr<HallEffect> shooter_plunger_;
757 ::std::unique_ptr<HallEffect> shooter_latch_;
758 ::std::unique_ptr<HallEffect> shooter_distal_;
759 ::std::unique_ptr<HallEffect> shooter_proximal_;
760 ::std::unique_ptr<Encoder> shooter_encoder_;
761
762 ::std::unique_ptr<HallEffect> claw_top_front_hall_;
763 ::std::unique_ptr<HallEffect> claw_top_calibration_hall_;
764 ::std::unique_ptr<HallEffect> claw_top_back_hall_;
765 ::std::unique_ptr<Encoder> claw_top_encoder_;
766
767 ::std::unique_ptr<HallEffect> claw_bottom_front_hall_;
768 ::std::unique_ptr<HallEffect> claw_bottom_calibration_hall_;
769 ::std::unique_ptr<HallEffect> claw_bottom_back_hall_;
770 ::std::unique_ptr<Encoder> claw_bottom_encoder_;
771
772 ::std::atomic<bool> run_;
773 DigitalGlitchFilter filter_;
774};
775
776class MotorWriter {
777 public:
778 MotorWriter()
779 : right_drivetrain_talon_(new Talon(2)),
780 left_drivetrain_talon_(new Talon(5)),
781 shooter_talon_(new Talon(6)),
782 top_claw_talon_(new Talon(1)),
783 bottom_claw_talon_(new Talon(0)),
784 left_tusk_talon_(new Talon(4)),
785 right_tusk_talon_(new Talon(3)),
786 intake1_talon_(new Talon(7)),
787 intake2_talon_(new Talon(8)),
788 left_shifter_(new Solenoid(6)),
789 right_shifter_(new Solenoid(7)),
790 shooter_latch_(new Solenoid(5)),
791 shooter_brake_(new Solenoid(4)),
792 compressor_(new Compressor()) {
793 compressor_->SetClosedLoopControl(true);
Austin Schuhdb516032014-12-28 00:12:38 -0800794 // right_drivetrain_talon_->EnableDeadbandElimination(true);
795 // left_drivetrain_talon_->EnableDeadbandElimination(true);
796 // shooter_talon_->EnableDeadbandElimination(true);
797 // top_claw_talon_->EnableDeadbandElimination(true);
798 // bottom_claw_talon_->EnableDeadbandElimination(true);
799 // left_tusk_talon_->EnableDeadbandElimination(true);
800 // right_tusk_talon_->EnableDeadbandElimination(true);
801 // intake1_talon_->EnableDeadbandElimination(true);
802 // intake2_talon_->EnableDeadbandElimination(true);
Austin Schuh010eb812014-10-25 18:06:49 -0700803 }
804
805 // Maximum age of an output packet before the motors get zeroed instead.
806 static const int kOutputMaxAgeMS = 20;
807 static constexpr ::aos::time::Time kOldLogInterval =
808 ::aos::time::Time::InSeconds(0.5);
809
810 void Run() {
811 //::aos::time::Time::EnableMockTime();
812 while (true) {
813 //::aos::time::Time::UpdateMockTime();
814 // 200 hz loop
815 ::aos::time::PhasedLoopXMS(5, 1000);
816 //::aos::time::Time::UpdateMockTime();
817
818 no_robot_state_.Print();
819 fake_robot_state_.Print();
820 sending_failed_.Print();
821
822 RunIteration();
823 }
824 }
825
826 virtual void RunIteration() {
827 ::aos::robot_state.FetchLatest();
828 if (!::aos::robot_state.get()) {
829 LOG_INTERVAL(no_robot_state_);
830 return;
831 }
832 if (::aos::robot_state->fake) {
833 LOG_INTERVAL(fake_robot_state_);
834 return;
835 }
836
837 // TODO(austin): Write the motor values out when they change! One thread
838 // per queue.
839 // TODO(austin): Figure out how to synchronize everything to the PWM update
840 // rate, or get the pulse to go out clocked off of this code. That would be
841 // awesome.
842 {
843 static auto &drivetrain = ::frc971::control_loops::drivetrain.output;
844 drivetrain.FetchLatest();
845 if (drivetrain.IsNewerThanMS(kOutputMaxAgeMS)) {
846 LOG_STRUCT(DEBUG, "will output", *drivetrain);
847 left_drivetrain_talon_->Set(-drivetrain->left_voltage / 12.0);
848 right_drivetrain_talon_->Set(drivetrain->right_voltage / 12.0);
849 left_shifter_->Set(drivetrain->left_high);
850 right_shifter_->Set(drivetrain->right_high);
851 } else {
852 left_drivetrain_talon_->Disable();
853 right_drivetrain_talon_->Disable();
854 LOG_INTERVAL(drivetrain_old_);
855 }
856 drivetrain_old_.Print();
857 }
858
859 {
860 static auto &shooter =
861 ::frc971::control_loops::shooter_queue_group.output;
862 shooter.FetchLatest();
863 if (shooter.IsNewerThanMS(kOutputMaxAgeMS)) {
864 LOG_STRUCT(DEBUG, "will output", *shooter);
865 shooter_talon_->Set(shooter->voltage / 12.0);
866 shooter_latch_->Set(!shooter->latch_piston);
867 shooter_brake_->Set(!shooter->brake_piston);
868 } else {
869 shooter_talon_->Disable();
870 shooter_brake_->Set(false); // engage the brake
871 LOG_INTERVAL(shooter_old_);
872 }
873 shooter_old_.Print();
874 }
875
876 {
877 static auto &claw = ::frc971::control_loops::claw_queue_group.output;
878 claw.FetchLatest();
879 if (claw.IsNewerThanMS(kOutputMaxAgeMS)) {
880 LOG_STRUCT(DEBUG, "will output", *claw);
881 intake1_talon_->Set(claw->intake_voltage / 12.0);
882 intake2_talon_->Set(claw->intake_voltage / 12.0);
883 bottom_claw_talon_->Set(-claw->bottom_claw_voltage / 12.0);
884 top_claw_talon_->Set(claw->top_claw_voltage / 12.0);
885 left_tusk_talon_->Set(claw->tusk_voltage / 12.0);
886 right_tusk_talon_->Set(-claw->tusk_voltage / 12.0);
887 } else {
888 intake1_talon_->Disable();
889 intake2_talon_->Disable();
890 bottom_claw_talon_->Disable();
891 top_claw_talon_->Disable();
892 left_tusk_talon_->Disable();
893 right_tusk_talon_->Disable();
894 LOG_INTERVAL(claw_old_);
895 }
896 claw_old_.Print();
897 }
898 }
899
900 SimpleLogInterval drivetrain_old_ =
901 SimpleLogInterval(kOldLogInterval, WARNING, "drivetrain too old");
902 SimpleLogInterval shooter_old_ =
903 SimpleLogInterval(kOldLogInterval, WARNING, "shooter too old");
904 SimpleLogInterval claw_old_ =
905 SimpleLogInterval(kOldLogInterval, WARNING, "claw too old");
906
907 ::std::unique_ptr<Talon> right_drivetrain_talon_;
908 ::std::unique_ptr<Talon> left_drivetrain_talon_;
909 ::std::unique_ptr<Talon> shooter_talon_;
910 ::std::unique_ptr<Talon> top_claw_talon_;
911 ::std::unique_ptr<Talon> bottom_claw_talon_;
912 ::std::unique_ptr<Talon> left_tusk_talon_;
913 ::std::unique_ptr<Talon> right_tusk_talon_;
914 ::std::unique_ptr<Talon> intake1_talon_;
915 ::std::unique_ptr<Talon> intake2_talon_;
916
917 ::std::unique_ptr<Solenoid> left_shifter_;
918 ::std::unique_ptr<Solenoid> right_shifter_;
919 ::std::unique_ptr<Solenoid> shooter_latch_;
920 ::std::unique_ptr<Solenoid> shooter_brake_;
921
922 ::std::unique_ptr<Compressor> compressor_;
923
924 ::aos::util::SimpleLogInterval no_robot_state_ =
925 ::aos::util::SimpleLogInterval(::aos::time::Time::InSeconds(0.5), INFO,
926 "no robot state -> not outputting");
927 ::aos::util::SimpleLogInterval fake_robot_state_ =
928 ::aos::util::SimpleLogInterval(::aos::time::Time::InSeconds(0.5), DEBUG,
929 "fake robot state -> not outputting");
930 ::aos::util::SimpleLogInterval sending_failed_ =
931 ::aos::util::SimpleLogInterval(::aos::time::Time::InSeconds(0.1), WARNING,
932 "sending outputs failed");
933};
934
935constexpr ::aos::time::Time MotorWriter::kOldLogInterval;
936
937class JoystickSender {
938 public:
939 JoystickSender() : run_(true) {}
940
941 void operator()() {
942 DriverStation *ds = DriverStation::GetInstance();
943 SetThreadRealtimePriority(29);
944 uint16_t team_id = ::aos::network::GetTeamNumber();
945
946 while (run_) {
947 ds->WaitForData();
948 auto new_state = ::aos::robot_state.MakeMessage();
949
950 new_state->test_mode = ds->IsAutonomous();
951 new_state->fms_attached = ds->IsFMSAttached();
952 new_state->enabled = ds->IsEnabled();
953 new_state->autonomous = ds->IsAutonomous();
954 new_state->team_id = team_id;
955 new_state->fake = false;
956
957 for (int i = 0; i < 4; ++i) {
958 new_state->joysticks[i].buttons = ds->GetStickButtons(i);
959 for (int j = 0; j < 4; ++j) {
960 new_state->joysticks[i].axis[j] = ds->GetStickAxis(i, j + 1);
961 }
962 }
963 LOG_STRUCT(DEBUG, "robot_state", *new_state);
964
965 if (!new_state.Send()) {
966 LOG(WARNING, "sending robot_state failed\n");
967 }
968 }
969 }
970
971 void Quit() { run_ = false; }
972
973 private:
974 ::std::atomic<bool> run_;
975};
Austin Schuh010eb812014-10-25 18:06:49 -0700976} // namespace output
977} // namespace frc971
978
979class WPILibRobot : public RobotBase {
980 public:
981 virtual void StartCompetition() {
982 ::aos::Init();
983 ::frc971::output::MotorWriter writer;
984 ::frc971::output::SensorReader reader;
985 ::std::thread reader_thread(::std::ref(reader));
986 ::frc971::output::JoystickSender joystick_sender;
987 ::std::thread joystick_thread(::std::ref(joystick_sender));
988 writer.Run();
989 LOG(ERROR, "Exiting WPILibRobot\n");
990 reader.Quit();
991 reader_thread.join();
992 joystick_sender.Quit();
993 joystick_thread.join();
994 ::aos::Cleanup();
995 }
996};
997
Austin Schuhdb516032014-12-28 00:12:38 -0800998
Austin Schuh010eb812014-10-25 18:06:49 -0700999START_ROBOT_CLASS(WPILibRobot);