blob: 737050a1704818e719adc34b3cd13173ed5c528a [file] [log] [blame]
Sabina Davis5ae0c7c2017-10-21 20:51:55 -07001#include <inttypes.h>
2#include <stdio.h>
3#include <string.h>
4#include <unistd.h>
5
6#include <array>
7#include <chrono>
8#include <cmath>
9#include <functional>
10#include <mutex>
11#include <thread>
12
13#include "AnalogInput.h"
14#include "DigitalGlitchFilter.h"
15#include "DriverStation.h"
16#include "Encoder.h"
17#include "Compressor.h"
18#include "VictorSP.h"
19#undef ERROR
20
21#include "aos/common/commonmath.h"
22#include "aos/common/logging/logging.h"
23#include "aos/common/logging/queue_logging.h"
24#include "aos/common/messages/robot_state.q.h"
25#include "aos/common/stl_mutex.h"
26#include "aos/common/time.h"
27#include "aos/common/util/compiler_memory_barrier.h"
28#include "aos/common/util/log_interval.h"
29#include "aos/common/util/phased_loop.h"
30#include "aos/linux_code/init.h"
31
32#include "frc971/control_loops/control_loops.q.h"
33#include "frc971/control_loops/drivetrain/drivetrain.q.h"
34#include "frc971/wpilib/ADIS16448.h"
35#include "frc971/wpilib/buffered_pcm.h"
36#include "frc971/wpilib/buffered_solenoid.h"
37#include "frc971/wpilib/gyro_sender.h"
38#include "frc971/wpilib/dma.h"
39#include "frc971/wpilib/dma_edge_counting.h"
40#include "frc971/wpilib/encoder_and_potentiometer.h"
41#include "frc971/wpilib/interrupt_edge_counting.h"
42#include "frc971/wpilib/joystick_sender.h"
43#include "frc971/wpilib/logging.q.h"
44#include "frc971/wpilib/loop_output_handler.h"
45#include "frc971/wpilib/pdp_fetcher.h"
46#include "frc971/wpilib/wpilib_interface.h"
47#include "frc971/wpilib/wpilib_robot_base.h"
48
49#include "y2017_bot3/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
50#include "frc971/control_loops/drivetrain/drivetrain.q.h"
51
52#ifndef M_PI
53#define M_PI 3.14159265358979323846
54#endif
55
56using ::frc971::control_loops::drivetrain_queue;
57using ::aos::monotonic_clock;
58namespace chrono = ::std::chrono;
59
60namespace y2017_bot3 {
61namespace wpilib {
62namespace {
63
64constexpr double kMaxBringupPower = 12.0;
65
66constexpr double kDrivetrainCyclesPerRevolution = 256;
67constexpr double kDrivetrainEncoderCountsPerRevolution =
68 kDrivetrainCyclesPerRevolution * 4;
69constexpr double kDrivetrainEncoderRatio =
70 1.0 * control_loops::drivetrain::kWheelRadius;
71constexpr double kMaxDrivetrainEncoderPulsesPerSecond =
72 control_loops::drivetrain::kFreeSpeed *
73 control_loops::drivetrain::kHighOutputRatio /
74 kDrivetrainEncoderRatio *
75 kDrivetrainEncoderCountsPerRevolution;
76
77// TODO(Brian): Fix the interpretation of the result of GetRaw here and in the
78// DMA stuff and then removing the * 2.0 in *_translate.
79// The low bit is direction.
80
81// TODO(brian): Replace this with ::std::make_unique once all our toolchains
82// have support.
83template <class T, class... U>
84std::unique_ptr<T> make_unique(U &&... u) {
85 return std::unique_ptr<T>(new T(std::forward<U>(u)...));
86}
87
88// TODO(brian): Use ::std::max instead once we have C++14 so that can be
89// constexpr.
90template <typename T>
91constexpr T max(T a, T b) {
92 return (a > b) ? a : b;
93}
94template <typename T, typename... Rest>
95constexpr T max(T a, T b, T c, Rest... rest) {
96 return max(max(a, b), c, rest...);
97}
98
99double hall_translate(double in) {
100 // Turn voltage from our 3-state halls into a ratio that the loop can use.
101 return in / 5.0;
102}
103
104double drivetrain_translate(int32_t in) {
105 return -static_cast<double>(in) / (256.0 /*cpr*/ * 4.0 /*4x*/) *
106 kDrivetrainEncoderRatio *
107 control_loops::drivetrain::kWheelRadius * 2.0 * M_PI;
108}
109
110double drivetrain_velocity_translate(double in) {
111 return (1.0 / in) / 256.0 /*cpr*/ *
112 kDrivetrainEncoderRatio *
113 control_loops::drivetrain::kWheelRadius * 2.0 * M_PI;
114}
115
116constexpr double kMaxFastEncoderPulsesPerSecond =
117 kMaxDrivetrainEncoderPulsesPerSecond;
118static_assert(kMaxFastEncoderPulsesPerSecond <= 1300000,
119 "fast encoders are too fast");
120
121// Class to send position messages with sensor readings to our loops.
122class SensorReader {
123 public:
124 SensorReader() {
125 // Set to filter out anything shorter than 1/4 of the minimum pulse width
126 // we should ever see.
127 fast_encoder_filter_.SetPeriodNanoSeconds(
128 static_cast<int>(1 / 4.0 /* built-in tolerance */ /
129 kMaxFastEncoderPulsesPerSecond * 1e9 +
130 0.5));
131 hall_filter_.SetPeriodNanoSeconds(100000);
132 }
133
134 void set_drivetrain_left_encoder(::std::unique_ptr<Encoder> encoder) {
135 fast_encoder_filter_.Add(encoder.get());
136 drivetrain_left_encoder_ = ::std::move(encoder);
137 }
138
139 void set_drivetrain_right_encoder(::std::unique_ptr<Encoder> encoder) {
140 fast_encoder_filter_.Add(encoder.get());
141 drivetrain_right_encoder_ = ::std::move(encoder);
142 }
143
144 void set_drivetrain_left_hall(::std::unique_ptr<AnalogInput> analog) {
145 drivetrain_left_hall_ = ::std::move(analog);
146 }
147
148 void set_drivetrain_right_hall(::std::unique_ptr<AnalogInput> analog) {
149 drivetrain_right_hall_ = ::std::move(analog);
150 }
151
152 void set_pwm_trigger(::std::unique_ptr<DigitalInput> pwm_trigger) {
153 medium_encoder_filter_.Add(pwm_trigger.get());
154 pwm_trigger_ = ::std::move(pwm_trigger);
155 }
156
157 // All of the DMA-related set_* calls must be made before this, and it
158 // doesn't
159 // hurt to do all of them.
160 void set_dma(::std::unique_ptr<DMA> dma) {
161 dma_synchronizer_.reset(
162 new ::frc971::wpilib::DMASynchronizer(::std::move(dma)));
163 }
164
165 void RunPWMDetecter() {
166 ::aos::SetCurrentThreadRealtimePriority(41);
167
168 pwm_trigger_->RequestInterrupts();
169 // Rising edge only.
170 pwm_trigger_->SetUpSourceEdge(true, false);
171
172 monotonic_clock::time_point last_posedge_monotonic =
173 monotonic_clock::min_time;
174
175 while (run_) {
176 auto ret = pwm_trigger_->WaitForInterrupt(1.0, true);
177 if (ret == InterruptableSensorBase::WaitResult::kRisingEdge) {
178 // Grab all the clocks.
179 const double pwm_fpga_time = pwm_trigger_->ReadRisingTimestamp();
180
181 aos_compiler_memory_barrier();
182 const double fpga_time_before = GetFPGATime() * 1e-6;
183 aos_compiler_memory_barrier();
184 const monotonic_clock::time_point monotonic_now =
185 monotonic_clock::now();
186 aos_compiler_memory_barrier();
187 const double fpga_time_after = GetFPGATime() * 1e-6;
188 aos_compiler_memory_barrier();
189
190 const double fpga_offset =
191 (fpga_time_after + fpga_time_before) / 2.0 - pwm_fpga_time;
192
193 // Compute when the edge was.
194 const monotonic_clock::time_point monotonic_edge =
195 monotonic_now - chrono::duration_cast<chrono::nanoseconds>(
196 chrono::duration<double>(fpga_offset));
197
198 LOG(INFO, "Got PWM pulse %f spread, %f offset, %lld trigger\n",
199 fpga_time_after - fpga_time_before, fpga_offset,
200 monotonic_edge.time_since_epoch().count());
201
202 // Compute bounds on the timestep and sampling times.
203 const double fpga_sample_length = fpga_time_after - fpga_time_before;
204 const chrono::nanoseconds elapsed_time =
205 monotonic_edge - last_posedge_monotonic;
206
207 last_posedge_monotonic = monotonic_edge;
208
209 // Verify that the values are sane.
210 if (fpga_sample_length > 2e-5 || fpga_sample_length < 0) {
211 continue;
212 }
213 if (fpga_offset < 0 || fpga_offset > 0.00015) {
214 continue;
215 }
216 if (elapsed_time >
217 chrono::microseconds(5050) + chrono::microseconds(4) ||
218 elapsed_time <
219 chrono::microseconds(5050) - chrono::microseconds(4)) {
220 continue;
221 }
222 // Good edge!
223 {
224 ::std::unique_lock<::aos::stl_mutex> locker(tick_time_mutex_);
225 last_tick_time_monotonic_timepoint_ = last_posedge_monotonic;
226 last_period_ = elapsed_time;
227 }
228 } else {
229 LOG(INFO, "PWM triggered %d\n", ret);
230 }
231 }
232 pwm_trigger_->CancelInterrupts();
233 }
234
235 void operator()() {
236 ::aos::SetCurrentThreadName("SensorReader");
237
238 my_pid_ = getpid();
239 ds_ = &DriverStation::GetInstance();
240
241 dma_synchronizer_->Start();
242
243 ::aos::time::PhasedLoop phased_loop(last_period_,
244 ::std::chrono::milliseconds(3));
245 chrono::nanoseconds filtered_period = last_period_;
246
247 ::std::thread pwm_detecter_thread(
248 ::std::bind(&SensorReader::RunPWMDetecter, this));
249
250 ::aos::SetCurrentThreadRealtimePriority(40);
251 while (run_) {
252 {
253 const int iterations = phased_loop.SleepUntilNext();
254 if (iterations != 1) {
255 LOG(WARNING, "SensorReader skipped %d iterations\n", iterations - 1);
256 }
257 }
258 RunIteration();
259
260 monotonic_clock::time_point last_tick_timepoint;
261 chrono::nanoseconds period;
262 {
263 ::std::unique_lock<::aos::stl_mutex> locker(tick_time_mutex_);
264 last_tick_timepoint = last_tick_time_monotonic_timepoint_;
265 period = last_period_;
266 }
267
268 if (last_tick_timepoint == monotonic_clock::min_time) {
269 continue;
270 }
271 chrono::nanoseconds new_offset = phased_loop.OffsetFromIntervalAndTime(
272 period, last_tick_timepoint + chrono::microseconds(2050));
273
274 // TODO(austin): If this is the first edge in a while, skip to it (plus
275 // an offset). Otherwise, slowly drift time to line up.
276
277 phased_loop.set_interval_and_offset(period, new_offset);
278 }
279 pwm_detecter_thread.join();
280 }
281
282 void RunIteration() {
283 ::frc971::wpilib::SendRobotState(my_pid_, ds_);
284
285 {
286 auto drivetrain_message = drivetrain_queue.position.MakeMessage();
287 drivetrain_message->right_encoder =
288 drivetrain_translate(drivetrain_right_encoder_->GetRaw());
289 drivetrain_message->right_speed =
290 drivetrain_velocity_translate(drivetrain_right_encoder_->GetPeriod());
291
292 drivetrain_message->left_encoder =
293 -drivetrain_translate(drivetrain_left_encoder_->GetRaw());
294 drivetrain_message->left_speed =
295 drivetrain_velocity_translate(drivetrain_left_encoder_->GetPeriod());
296
297 drivetrain_message->left_shifter_position =
298 hall_translate(drivetrain_left_hall_->GetVoltage());
299 drivetrain_message->right_shifter_position =
300 hall_translate(drivetrain_right_hall_->GetVoltage());
301
302 drivetrain_message.Send();
303 }
304
305 dma_synchronizer_->RunIteration();
306 }
307
308 void Quit() { run_ = false; }
309
310 private:
311 double encoder_translate(int32_t value, double counts_per_revolution,
312 double ratio) {
313 return static_cast<double>(value) / counts_per_revolution * ratio *
314 (2.0 * M_PI);
315 }
316
317 int32_t my_pid_;
318 DriverStation *ds_;
319
320 // Mutex to manage access to the period and tick time variables.
321 ::aos::stl_mutex tick_time_mutex_;
322 monotonic_clock::time_point last_tick_time_monotonic_timepoint_ =
323 monotonic_clock::min_time;
324 chrono::nanoseconds last_period_ = chrono::microseconds(5050);
325
326 ::std::unique_ptr<::frc971::wpilib::DMASynchronizer> dma_synchronizer_;
327
328 ::std::unique_ptr<Encoder> drivetrain_left_encoder_,
329 drivetrain_right_encoder_;
330
331 ::std::unique_ptr<AnalogInput> drivetrain_left_hall_, drivetrain_right_hall_;
332
333 ::std::unique_ptr<DigitalInput> pwm_trigger_;
334
335 ::std::atomic<bool> run_{true};
336
337 DigitalGlitchFilter fast_encoder_filter_, medium_encoder_filter_, hall_filter_;
338};
339
340class SolenoidWriter {
341 public:
342 SolenoidWriter(const ::std::unique_ptr<::frc971::wpilib::BufferedPcm> &pcm)
343 : pcm_(pcm),
344 drivetrain_(".y2017_bot3.control_loops.drivetrain_queue.output"){}
345 void set_compressor(::std::unique_ptr<Compressor> compressor) {
346 compressor_ = ::std::move(compressor);
347 }
348
349 void set_drivetrain_shifter(
350 ::std::unique_ptr<::frc971::wpilib::BufferedSolenoid> s) {
351 drivetrain_shifter_ = ::std::move(s);
352 }
353
354 void operator()() {
355 compressor_->Start();
356 ::aos::SetCurrentThreadName("Solenoids");
357 ::aos::SetCurrentThreadRealtimePriority(27);
358
359 ::aos::time::PhasedLoop phased_loop(::std::chrono::milliseconds(20),
360 ::std::chrono::milliseconds(1));
361
362 while (run_) {
363 {
364 int iterations = phased_loop.SleepUntilNext();
365 if (iterations != 1) {
366 LOG(DEBUG, "Solenoids skipped %d iterations\n", iterations - 1);
367 }
368 }
369
370 {
371 drivetrain_.FetchLatest();
372 if (drivetrain_.get()) {
373 LOG_STRUCT(DEBUG, "solenoids", *drivetrain_);
374 drivetrain_shifter_->Set(
375 !(drivetrain_->left_high || drivetrain_->right_high));
376 }
377 }
378
379 {
380 ::frc971::wpilib::PneumaticsToLog to_log;
381 {
382 to_log.compressor_on = compressor_->Enabled();
383 }
384
385 pcm_->Flush();
386 to_log.read_solenoids = pcm_->GetAll();
387 LOG_STRUCT(DEBUG, "pneumatics info", to_log);
388 }
389 }
390 }
391
392 void Quit() { run_ = false; }
393
394 private:
395 const ::std::unique_ptr<::frc971::wpilib::BufferedPcm> &pcm_;
396 ::std::unique_ptr<::frc971::wpilib::BufferedSolenoid> drivetrain_shifter_;
397
398 ::std::unique_ptr<Compressor> compressor_;
399
400 ::aos::Queue<::frc971::control_loops::DrivetrainQueue::Output> drivetrain_;
401
402 ::std::atomic<bool> run_{true};
403};
404
405class DrivetrainWriter : public ::frc971::wpilib::LoopOutputHandler {
406 public:
407 void set_drivetrain_left_victor(::std::unique_ptr<::frc::VictorSP> t) {
408 drivetrain_left_victor_ = ::std::move(t);
409 }
410
411 void set_drivetrain_right_victor(::std::unique_ptr<::frc::VictorSP> t) {
412 drivetrain_right_victor_ = ::std::move(t);
413 };
414 private:
415 virtual void Read() override {
416 ::frc971::control_loops::drivetrain_queue.output.FetchAnother();
417 }
418
419 virtual void Write() override {
420 auto &queue = ::frc971::control_loops::drivetrain_queue.output;
421 LOG_STRUCT(DEBUG, "will output", *queue);
422 drivetrain_left_victor_->SetSpeed(-queue->left_voltage / 12.0);
423 drivetrain_right_victor_->SetSpeed(queue->right_voltage / 12.0);
424 }
425
426 virtual void Stop() override {
427 LOG(WARNING, "drivetrain output too old\n");
428 drivetrain_left_victor_->SetDisabled();
429 drivetrain_right_victor_->SetDisabled();
430 }
431
432 ::std::unique_ptr<::frc::VictorSP> drivetrain_left_victor_,
433 drivetrain_right_victor_;
434};
435
436class WPILibRobot : public ::frc971::wpilib::WPILibRobotBase {
437 public:
438 ::std::unique_ptr<Encoder> make_encoder(int index) {
439 return make_unique<Encoder>(10 + index * 2, 11 + index * 2, false,
440 Encoder::k4X);
441 }
442
443 void Run() override {
444 ::aos::InitNRT();
445 ::aos::SetCurrentThreadName("StartCompetition");
446
447 ::frc971::wpilib::JoystickSender joystick_sender;
448 ::std::thread joystick_thread(::std::ref(joystick_sender));
449
450 ::frc971::wpilib::PDPFetcher pdp_fetcher;
451 ::std::thread pdp_fetcher_thread(::std::ref(pdp_fetcher));
452 SensorReader reader;
453
454 // TODO(sabina): Update port numbers
455 reader.set_drivetrain_left_encoder(make_encoder(0));
456 reader.set_drivetrain_right_encoder(make_encoder(1));
457 reader.set_drivetrain_left_hall(make_unique<AnalogInput>(0));
458 reader.set_drivetrain_right_hall(make_unique<AnalogInput>(1));
459
460 reader.set_pwm_trigger(make_unique<DigitalInput>(7));
461 reader.set_dma(make_unique<DMA>());
462 ::std::thread reader_thread(::std::ref(reader));
463
464 ::frc971::wpilib::GyroSender gyro_sender;
465 ::std::thread gyro_thread(::std::ref(gyro_sender));
466
467 DrivetrainWriter drivetrain_writer;
468 drivetrain_writer.set_drivetrain_left_victor(
469 ::std::unique_ptr<::frc::VictorSP>(new ::frc::VictorSP(7)));
470 drivetrain_writer.set_drivetrain_right_victor(
471 ::std::unique_ptr<::frc::VictorSP>(new ::frc::VictorSP(3)));
472 ::std::thread drivetrain_writer_thread(::std::ref(drivetrain_writer));
473
474 ::std::unique_ptr<::frc971::wpilib::BufferedPcm> pcm(
475 new ::frc971::wpilib::BufferedPcm());
476 SolenoidWriter solenoid_writer(pcm);
477 solenoid_writer.set_drivetrain_shifter(pcm->MakeSolenoid(0));
478
479 solenoid_writer.set_compressor(make_unique<Compressor>());
480
481 ::std::thread solenoid_thread(::std::ref(solenoid_writer));
482
483 // Wait forever. Not much else to do...
484 while (true) {
485 const int r = select(0, nullptr, nullptr, nullptr, nullptr);
486 if (r != 0) {
487 PLOG(WARNING, "infinite select failed");
488 } else {
489 PLOG(WARNING, "infinite select succeeded??\n");
490 }
491 }
492
493 LOG(ERROR, "Exiting WPILibRobot\n");
494
495 joystick_sender.Quit();
496 joystick_thread.join();
497 pdp_fetcher.Quit();
498 pdp_fetcher_thread.join();
499 reader.Quit();
500 reader_thread.join();
501 gyro_sender.Quit();
502 gyro_thread.join();
503
504 drivetrain_writer.Quit();
505 drivetrain_writer_thread.join();
506 solenoid_writer.Quit();
507 solenoid_thread.join();
508
509 ::aos::Cleanup();
510 }
511};
512
513} // namespace
514} // namespace wpilib
515} // namespace y2017_bot3
516
517AOS_ROBOT_CLASS(::y2017_bot3::wpilib::WPILibRobot);