blob: 5d78649b0cd58fa19562af4892bd9e1a4b33e571 [file] [log] [blame]
Sabina Davisabeae332019-02-01 21:12:57 -08001#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 "frc971/wpilib/ahal/AnalogInput.h"
14#include "frc971/wpilib/ahal/Counter.h"
15#include "frc971/wpilib/ahal/DigitalGlitchFilter.h"
16#include "frc971/wpilib/ahal/DriverStation.h"
17#include "frc971/wpilib/ahal/Encoder.h"
18#include "frc971/wpilib/ahal/VictorSP.h"
19#undef ERROR
20
21#include "aos/commonmath.h"
22#include "aos/init.h"
23#include "aos/logging/logging.h"
24#include "aos/logging/queue_logging.h"
25#include "aos/make_unique.h"
26#include "aos/stl_mutex/stl_mutex.h"
27#include "aos/time/time.h"
28#include "aos/util/compiler_memory_barrier.h"
29#include "aos/util/log_interval.h"
30#include "aos/util/phased_loop.h"
31#include "aos/util/wrapping_counter.h"
32
33#include "frc971/autonomous/auto.q.h"
34#include "frc971/control_loops/drivetrain/drivetrain.q.h"
35#include "frc971/wpilib/ADIS16448.h"
36#include "frc971/wpilib/buffered_pcm.h"
37#include "frc971/wpilib/buffered_solenoid.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#ifndef M_PI
50#define M_PI 3.14159265358979323846
51#endif
52
53using ::frc971::control_loops::drivetrain_queue;
54using ::aos::monotonic_clock;
55namespace chrono = ::std::chrono;
56using aos::make_unique;
57
58namespace y2019 {
59namespace wpilib {
60namespace {
61
62constexpr double kMaxBringupPower = 12.0;
63
64// TODO(Brian): Fix the interpretation of the result of GetRaw here and in the
65// DMA stuff and then removing the * 2.0 in *_translate.
66// The low bit is direction.
67
68// TODO(brian): Use ::std::max instead once we have C++14 so that can be
69// constexpr.
70template <typename T>
71constexpr T max(T a, T b) {
72 return (a > b) ? a : b;
73}
74
75template <typename T, typename... Rest>
76constexpr T max(T a, T b, T c, Rest... rest) {
77 return max(max(a, b), c, rest...);
78}
79
80double drivetrain_translate(int32_t in) {
81 return ((static_cast<double>(in)
82 /* / Values::kDrivetrainEncoderCountsPerRevolution()) *
83 (2.0 * M_PI)) *
84 Values::kDrivetrainEncoderRatio() *
85 control_loops::drivetrain::kWheelRadius*/));
86}
87
88double drivetrain_velocity_translate(double in) {
89 return (((1.0 / in) /* / Values::kDrivetrainCyclesPerRevolution()) *
90 (2.0 * M_PI)) *
91 Values::kDrivetrainEncoderRatio() *
92 control_loops::drivetrain::kWheelRadius*/));
93}
94
95constexpr double kMaxFastEncoderPulsesPerSecond =
96 max(/*Values::kMaxDrivetrainEncoderPulsesPerSecond(),
97 Values::kMaxIntakeMotorEncoderPulsesPerSecond()*/ 1.0, 1.0);
98static_assert(kMaxFastEncoderPulsesPerSecond <= 1300000,
99 "fast encoders are too fast");
100
101constexpr double kMaxMediumEncoderPulsesPerSecond =
102 max(/*Values::kMaxProximalEncoderPulsesPerSecond(),
103 Values::kMaxDistalEncoderPulsesPerSecond()*/ 1.0, 1.0);
104static_assert(kMaxMediumEncoderPulsesPerSecond <= 400000,
105 "medium encoders are too fast");
106
107// Class to send position messages with sensor readings to our loops.
108class SensorReader {
109 public:
110 SensorReader() {
111 // Set to filter out anything shorter than 1/4 of the minimum pulse width
112 // we should ever see.
113 fast_encoder_filter_.SetPeriodNanoSeconds(
114 static_cast<int>(1 / 4.0 /* built-in tolerance */ /
115 kMaxFastEncoderPulsesPerSecond * 1e9 +
116 0.5));
117 medium_encoder_filter_.SetPeriodNanoSeconds(
118 static_cast<int>(1 / 4.0 /* built-in tolerance */ /
119 kMaxMediumEncoderPulsesPerSecond * 1e9 +
120 0.5));
121 hall_filter_.SetPeriodNanoSeconds(100000);
122 }
123
124 // Left drivetrain side.
125 void set_drivetrain_left_encoder(::std::unique_ptr<frc::Encoder> encoder) {
126 fast_encoder_filter_.Add(encoder.get());
127 drivetrain_left_encoder_ = ::std::move(encoder);
128 }
129
130 // Right drivetrain side.
131 void set_drivetrain_right_encoder(::std::unique_ptr<frc::Encoder> encoder) {
132 fast_encoder_filter_.Add(encoder.get());
133 drivetrain_right_encoder_ = ::std::move(encoder);
134 }
135
136 void set_pwm_trigger(::std::unique_ptr<frc::DigitalInput> pwm_trigger) {
137 medium_encoder_filter_.Add(pwm_trigger.get());
138 pwm_trigger_ = ::std::move(pwm_trigger);
139 }
140
141 // All of the DMA-related set_* calls must be made before this, and it
142 // doesn't hurt to do all of them.
143 void set_dma(::std::unique_ptr<DMA> dma) {
144 dma_synchronizer_.reset(
145 new ::frc971::wpilib::DMASynchronizer(::std::move(dma)));
146 }
147
148 void RunPWMDetecter() {
149 ::aos::SetCurrentThreadRealtimePriority(41);
150
151 pwm_trigger_->RequestInterrupts();
152 // Rising edge only.
153 pwm_trigger_->SetUpSourceEdge(true, false);
154
155 monotonic_clock::time_point last_posedge_monotonic =
156 monotonic_clock::min_time;
157
158 while (run_) {
159 auto ret = pwm_trigger_->WaitForInterrupt(1.0, true);
160 if (ret == frc::InterruptableSensorBase::WaitResult::kRisingEdge) {
161 // Grab all the clocks.
162 const double pwm_fpga_time = pwm_trigger_->ReadRisingTimestamp();
163
164 aos_compiler_memory_barrier();
165 const double fpga_time_before = frc::GetFPGATime() * 1e-6;
166 aos_compiler_memory_barrier();
167 const monotonic_clock::time_point monotonic_now =
168 monotonic_clock::now();
169 aos_compiler_memory_barrier();
170 const double fpga_time_after = frc::GetFPGATime() * 1e-6;
171 aos_compiler_memory_barrier();
172
173 const double fpga_offset =
174 (fpga_time_after + fpga_time_before) / 2.0 - pwm_fpga_time;
175
176 // Compute when the edge was.
177 const monotonic_clock::time_point monotonic_edge =
178 monotonic_now - chrono::duration_cast<chrono::nanoseconds>(
179 chrono::duration<double>(fpga_offset));
180
181 LOG(DEBUG, "Got PWM pulse %f spread, %f offset, %lld trigger\n",
182 fpga_time_after - fpga_time_before, fpga_offset,
183 monotonic_edge.time_since_epoch().count());
184
185 // Compute bounds on the timestep and sampling times.
186 const double fpga_sample_length = fpga_time_after - fpga_time_before;
187 const chrono::nanoseconds elapsed_time =
188 monotonic_edge - last_posedge_monotonic;
189
190 last_posedge_monotonic = monotonic_edge;
191
192 // Verify that the values are sane.
193 if (fpga_sample_length > 2e-5 || fpga_sample_length < 0) {
194 continue;
195 }
196 if (fpga_offset < 0 || fpga_offset > 0.00015) {
197 continue;
198 }
199 if (elapsed_time >
200 chrono::microseconds(5050) + chrono::microseconds(4) ||
201 elapsed_time <
202 chrono::microseconds(5050) - chrono::microseconds(4)) {
203 continue;
204 }
205 // Good edge!
206 {
207 ::std::unique_lock<::aos::stl_mutex> locker(tick_time_mutex_);
208 last_tick_time_monotonic_timepoint_ = last_posedge_monotonic;
209 last_period_ = elapsed_time;
210 }
211 } else {
212 LOG(INFO, "PWM triggered %d\n", ret);
213 }
214 }
215 pwm_trigger_->CancelInterrupts();
216 }
217
218 void operator()() {
219 ::aos::SetCurrentThreadName("SensorReader");
220
221 my_pid_ = getpid();
222
223 dma_synchronizer_->Start();
224
225 ::aos::time::PhasedLoop phased_loop(last_period_,
226 ::std::chrono::milliseconds(3));
227 chrono::nanoseconds filtered_period = last_period_;
228
229 ::std::thread pwm_detecter_thread(
230 ::std::bind(&SensorReader::RunPWMDetecter, this));
231
232 ::aos::SetCurrentThreadRealtimePriority(40);
233 while (run_) {
234 {
235 const int iterations = phased_loop.SleepUntilNext();
236 if (iterations != 1) {
237 LOG(WARNING, "SensorReader skipped %d iterations\n", iterations - 1);
238 }
239 }
240 RunIteration();
241
242 monotonic_clock::time_point last_tick_timepoint;
243 chrono::nanoseconds period;
244 {
245 ::std::unique_lock<::aos::stl_mutex> locker(tick_time_mutex_);
246 last_tick_timepoint = last_tick_time_monotonic_timepoint_;
247 period = last_period_;
248 }
249
250 if (last_tick_timepoint == monotonic_clock::min_time) {
251 continue;
252 }
253 chrono::nanoseconds new_offset = phased_loop.OffsetFromIntervalAndTime(
254 period, last_tick_timepoint + chrono::microseconds(2050));
255
256 // TODO(austin): If this is the first edge in a while, skip to it (plus
257 // an offset). Otherwise, slowly drift time to line up.
258
259 phased_loop.set_interval_and_offset(period, new_offset);
260 }
261 pwm_detecter_thread.join();
262 }
263
264 void RunIteration() {
265 ::frc971::wpilib::SendRobotState(my_pid_);
266
267 {
268 auto drivetrain_message = drivetrain_queue.position.MakeMessage();
269 drivetrain_message->left_encoder =
270 drivetrain_translate(drivetrain_left_encoder_->GetRaw());
271 drivetrain_message->left_speed =
272 drivetrain_velocity_translate(drivetrain_left_encoder_->GetPeriod());
273
274 drivetrain_message->right_encoder =
275 -drivetrain_translate(drivetrain_right_encoder_->GetRaw());
276 drivetrain_message->right_speed = -drivetrain_velocity_translate(
277 drivetrain_right_encoder_->GetPeriod());
278
279 drivetrain_message.Send();
280 }
281
282 dma_synchronizer_->RunIteration();
283 }
284
285 void Quit() { run_ = false; }
286
287 private:
288 double encoder_translate(int32_t value, double counts_per_revolution,
289 double ratio) {
290 return static_cast<double>(value) / counts_per_revolution * ratio *
291 (2.0 * M_PI);
292 }
293
294 int32_t my_pid_;
295
296 // Mutex to manage access to the period and tick time variables.
297 ::aos::stl_mutex tick_time_mutex_;
298 monotonic_clock::time_point last_tick_time_monotonic_timepoint_ =
299 monotonic_clock::min_time;
300 chrono::nanoseconds last_period_ = chrono::microseconds(5050);
301
302 ::std::unique_ptr<::frc971::wpilib::DMASynchronizer> dma_synchronizer_;
303
304 frc::DigitalGlitchFilter fast_encoder_filter_, medium_encoder_filter_,
305 hall_filter_;
306
307 ::std::unique_ptr<frc::Encoder> drivetrain_left_encoder_,
308 drivetrain_right_encoder_;
309
310 ::std::unique_ptr<frc::DigitalInput> pwm_trigger_;
311
312 ::std::atomic<bool> run_{true};
313};
314
315class DrivetrainWriter : public ::frc971::wpilib::LoopOutputHandler {
316 public:
317 void set_drivetrain_left_victor(::std::unique_ptr<::frc::VictorSP> t) {
318 drivetrain_left_victor_ = ::std::move(t);
319 }
320
321 void set_drivetrain_right_victor(::std::unique_ptr<::frc::VictorSP> t) {
322 drivetrain_right_victor_ = ::std::move(t);
323 }
324
325 private:
326 virtual void Read() override {
327 ::frc971::control_loops::drivetrain_queue.output.FetchAnother();
328 }
329
330 virtual void Write() override {
331 auto &queue = ::frc971::control_loops::drivetrain_queue.output;
332 LOG_STRUCT(DEBUG, "will output", *queue);
333 drivetrain_left_victor_->SetSpeed(
334 ::aos::Clip(queue->left_voltage, -12.0, 12.0) / 12.0);
335 drivetrain_right_victor_->SetSpeed(
336 ::aos::Clip(-queue->right_voltage, -12.0, 12.0) / 12.0);
337 }
338
339 virtual void Stop() override {
340 LOG(WARNING, "drivetrain output too old\n");
341 drivetrain_left_victor_->SetDisabled();
342 drivetrain_right_victor_->SetDisabled();
343 }
344
345 ::std::unique_ptr<::frc::VictorSP> drivetrain_left_victor_,
346 drivetrain_right_victor_;
347};
348
349class WPILibRobot : public ::frc971::wpilib::WPILibRobotBase {
350 public:
351 ::std::unique_ptr<frc::Encoder> make_encoder(int index) {
352 return make_unique<frc::Encoder>(10 + index * 2, 11 + index * 2, false,
353 frc::Encoder::k4X);
354 }
355
356 void Run() override {
357 ::aos::InitNRT();
358 ::aos::SetCurrentThreadName("StartCompetition");
359
360 ::frc971::wpilib::JoystickSender joystick_sender;
361 ::std::thread joystick_thread(::std::ref(joystick_sender));
362
363 ::frc971::wpilib::PDPFetcher pdp_fetcher;
364 ::std::thread pdp_fetcher_thread(::std::ref(pdp_fetcher));
365 SensorReader reader;
366
367 // TODO(Sabina): Update port numbers(Sensors and Victors)
368 reader.set_drivetrain_left_encoder(make_encoder(0));
369 reader.set_drivetrain_right_encoder(make_encoder(1));
370
371 reader.set_pwm_trigger(make_unique<frc::DigitalInput>(25));
372
373 reader.set_dma(make_unique<DMA>());
374 ::std::thread reader_thread(::std::ref(reader));
375
376 auto imu_trigger = make_unique<frc::DigitalInput>(5);
377 ::frc971::wpilib::ADIS16448 imu(frc::SPI::Port::kOnboardCS1,
378 imu_trigger.get());
379 imu.SetDummySPI(frc::SPI::Port::kOnboardCS2);
380 auto imu_reset = make_unique<frc::DigitalOutput>(6);
381 imu.set_reset(imu_reset.get());
382 ::std::thread imu_thread(::std::ref(imu));
383
384 // While as of 2/9/18 the drivetrain Victors are SPX, it appears as though
385 // they are identical, as far as DrivetrainWriter is concerned, to the SP
386 // variety so all the Victors are written as SPs.
387
388 DrivetrainWriter drivetrain_writer;
389 drivetrain_writer.set_drivetrain_left_victor(
390 ::std::unique_ptr<::frc::VictorSP>(new ::frc::VictorSP(2)));
391 drivetrain_writer.set_drivetrain_right_victor(
392 ::std::unique_ptr<::frc::VictorSP>(new ::frc::VictorSP(3)));
393 ::std::thread drivetrain_writer_thread(::std::ref(drivetrain_writer));
394
395 // Wait forever. Not much else to do...
396 while (true) {
397 const int r = select(0, nullptr, nullptr, nullptr, nullptr);
398 if (r != 0) {
399 PLOG(WARNING, "infinite select failed");
400 } else {
401 PLOG(WARNING, "infinite select succeeded??\n");
402 }
403 }
404
405 LOG(ERROR, "Exiting WPILibRobot\n");
406
407 joystick_sender.Quit();
408 joystick_thread.join();
409 pdp_fetcher.Quit();
410 pdp_fetcher_thread.join();
411 reader.Quit();
412 reader_thread.join();
413 imu.Quit();
414 imu_thread.join();
415
416 drivetrain_writer.Quit();
417 drivetrain_writer_thread.join();
418
419 ::aos::Cleanup();
420 }
421};
422
423} // namespace
424} // namespace wpilib
425} // namespace y2019
426
427AOS_ROBOT_CLASS(::y2019::wpilib::WPILibRobot);