blob: 9b8df5dd0e68f6ef730575b5770df6cf382d463f [file] [log] [blame]
Ariv Diggi0af59c02023-10-07 13:15:39 -07001#include <unistd.h>
2
3#include <array>
4#include <chrono>
5#include <cinttypes>
6#include <cmath>
7#include <cstdio>
8#include <cstring>
9#include <functional>
10#include <memory>
11#include <mutex>
12#include <thread>
13
14#include "ctre/phoenix/CANifier.h"
15
16#include "frc971/wpilib/ahal/AnalogInput.h"
17#include "frc971/wpilib/ahal/Counter.h"
18#include "frc971/wpilib/ahal/DigitalGlitchFilter.h"
19#include "frc971/wpilib/ahal/DriverStation.h"
20#include "frc971/wpilib/ahal/Encoder.h"
21#include "frc971/wpilib/ahal/Servo.h"
22#include "frc971/wpilib/ahal/TalonFX.h"
23#include "frc971/wpilib/ahal/VictorSP.h"
24#undef ERROR
25
26#include "ctre/phoenix/cci/Diagnostics_CCI.h"
Ariv Diggi0af59c02023-10-07 13:15:39 -070027#include "ctre/phoenix6/TalonFX.hpp"
28
29#include "aos/commonmath.h"
30#include "aos/containers/sized_array.h"
31#include "aos/events/event_loop.h"
32#include "aos/events/shm_event_loop.h"
33#include "aos/init.h"
34#include "aos/logging/logging.h"
35#include "aos/realtime.h"
36#include "aos/time/time.h"
37#include "aos/util/log_interval.h"
38#include "aos/util/phased_loop.h"
39#include "aos/util/wrapping_counter.h"
40#include "frc971/autonomous/auto_mode_generated.h"
41#include "frc971/can_configuration_generated.h"
42#include "frc971/control_loops/drivetrain/drivetrain_can_position_generated.h"
43#include "frc971/control_loops/drivetrain/drivetrain_position_generated.h"
44#include "frc971/input/robot_state_generated.h"
45#include "frc971/queues/gyro_generated.h"
46#include "frc971/wpilib/ADIS16448.h"
47#include "frc971/wpilib/buffered_pcm.h"
48#include "frc971/wpilib/buffered_solenoid.h"
49#include "frc971/wpilib/dma.h"
50#include "frc971/wpilib/drivetrain_writer.h"
51#include "frc971/wpilib/encoder_and_potentiometer.h"
52#include "frc971/wpilib/joystick_sender.h"
53#include "frc971/wpilib/logging_generated.h"
54#include "frc971/wpilib/loop_output_handler.h"
55#include "frc971/wpilib/pdp_fetcher.h"
56#include "frc971/wpilib/sensor_reader.h"
57#include "frc971/wpilib/wpilib_robot_base.h"
58#include "y2023_bot3/constants.h"
59#include "y2023_bot3/control_loops/superstructure/led_indicator.h"
60#include "y2023_bot3/control_loops/superstructure/superstructure_output_generated.h"
61#include "y2023_bot3/control_loops/superstructure/superstructure_position_generated.h"
62
63DEFINE_bool(ctre_diag_server, false,
64 "If true, enable the diagnostics server for interacting with "
65 "devices on the CAN bus using Phoenix Tuner");
66
67using ::aos::monotonic_clock;
68using ::y2023_bot3::constants::Values;
69namespace superstructure = ::y2023_bot3::control_loops::superstructure;
70namespace drivetrain = ::y2023_bot3::control_loops::drivetrain;
71namespace chrono = ::std::chrono;
72using std::make_unique;
73
74namespace y2023_bot3 {
75namespace wpilib {
76namespace {
77
78constexpr double kMaxBringupPower = 12.0;
79
80// TODO(Brian): Fix the interpretation of the result of GetRaw here and in the
81// DMA stuff and then removing the * 2.0 in *_translate.
82// The low bit is direction.
83
84double drivetrain_velocity_translate(double in) {
85 return (((1.0 / in) / Values::kDrivetrainCyclesPerRevolution()) *
86 (2.0 * M_PI)) *
87 Values::kDrivetrainEncoderRatio() *
88 control_loops::drivetrain::kWheelRadius;
89}
90
91constexpr double kMaxFastEncoderPulsesPerSecond = std::max({
92 Values::kMaxDrivetrainEncoderPulsesPerSecond(),
93});
94static_assert(kMaxFastEncoderPulsesPerSecond <= 1300000,
95 "fast encoders are too fast");
96
97} // namespace
98
99static constexpr int kCANFalconCount = 6;
100static constexpr units::frequency::hertz_t kCANUpdateFreqHz = 200_Hz;
101
102class Falcon {
103 public:
104 Falcon(int device_id, std::string canbus,
105 std::vector<ctre::phoenix6::BaseStatusSignal *> *signals)
106 : talon_(device_id, canbus),
107 device_id_(device_id),
108 device_temp_(talon_.GetDeviceTemp()),
109 supply_voltage_(talon_.GetSupplyVoltage()),
110 supply_current_(talon_.GetSupplyCurrent()),
111 torque_current_(talon_.GetTorqueCurrent()),
112 position_(talon_.GetPosition()),
113 duty_cycle_(talon_.GetDutyCycle()) {
114 // device temp is not timesynced so don't add it to the list of signals
115 device_temp_.SetUpdateFrequency(kCANUpdateFreqHz);
116
117 CHECK_NOTNULL(signals);
118
119 supply_voltage_.SetUpdateFrequency(kCANUpdateFreqHz);
120 signals->push_back(&supply_voltage_);
121
122 supply_current_.SetUpdateFrequency(kCANUpdateFreqHz);
123 signals->push_back(&supply_current_);
124
125 torque_current_.SetUpdateFrequency(kCANUpdateFreqHz);
126 signals->push_back(&torque_current_);
127
128 position_.SetUpdateFrequency(kCANUpdateFreqHz);
129 signals->push_back(&position_);
130
131 duty_cycle_.SetUpdateFrequency(kCANUpdateFreqHz);
132 signals->push_back(&duty_cycle_);
133 }
134
135 void PrintConfigs() {
136 ctre::phoenix6::configs::TalonFXConfiguration configuration;
137 ctre::phoenix::StatusCode status =
138 talon_.GetConfigurator().Refresh(configuration);
139 if (!status.IsOK()) {
140 AOS_LOG(ERROR, "Failed to get falcon configuration: %s: %s",
141 status.GetName(), status.GetDescription());
142 }
143 AOS_LOG(INFO, "configuration: %s", configuration.ToString().c_str());
144 }
145
146 void WriteConfigs(ctre::phoenix6::signals::InvertedValue invert) {
147 inverted_ = invert;
148
149 ctre::phoenix6::configs::CurrentLimitsConfigs current_limits;
150 current_limits.StatorCurrentLimit =
151 constants::Values::kDrivetrainStatorCurrentLimit();
152 current_limits.StatorCurrentLimitEnable = true;
153 current_limits.SupplyCurrentLimit =
154 constants::Values::kDrivetrainSupplyCurrentLimit();
155 current_limits.SupplyCurrentLimitEnable = true;
156
157 ctre::phoenix6::configs::MotorOutputConfigs output_configs;
158 output_configs.NeutralMode =
159 ctre::phoenix6::signals::NeutralModeValue::Brake;
160 output_configs.DutyCycleNeutralDeadband = 0;
161
162 output_configs.Inverted = inverted_;
163
164 ctre::phoenix6::configs::TalonFXConfiguration configuration;
165 configuration.CurrentLimits = current_limits;
166 configuration.MotorOutput = output_configs;
167
168 ctre::phoenix::StatusCode status =
169 talon_.GetConfigurator().Apply(configuration);
170 if (!status.IsOK()) {
171 AOS_LOG(ERROR, "Failed to set falcon configuration: %s: %s",
172 status.GetName(), status.GetDescription());
173 }
174
175 PrintConfigs();
176 }
177
178 ctre::phoenix6::hardware::TalonFX *talon() { return &talon_; }
179
180 flatbuffers::Offset<frc971::control_loops::CANFalcon> WritePosition(
181 flatbuffers::FlatBufferBuilder *fbb) {
182 frc971::control_loops::CANFalcon::Builder builder(*fbb);
183 builder.add_id(device_id_);
184 builder.add_device_temp(device_temp());
185 builder.add_supply_voltage(supply_voltage());
186 builder.add_supply_current(supply_current());
187 builder.add_torque_current(torque_current());
188 builder.add_duty_cycle(duty_cycle());
189
190 double invert =
191 (inverted_ == ctre::phoenix6::signals::InvertedValue::Clockwise_Positive
192 ? 1
193 : -1);
194
195 builder.add_position(
196 constants::Values::DrivetrainCANEncoderToMeters(position()) * invert);
197
198 return builder.Finish();
199 }
200
201 int device_id() const { return device_id_; }
202 float device_temp() const { return device_temp_.GetValue().value(); }
203 float supply_voltage() const { return supply_voltage_.GetValue().value(); }
204 float supply_current() const { return supply_current_.GetValue().value(); }
205 float torque_current() const { return torque_current_.GetValue().value(); }
206 float duty_cycle() const { return duty_cycle_.GetValue().value(); }
207 float position() const { return position_.GetValue().value(); }
208
209 // returns the monotonic timestamp of the latest timesynced reading in the
210 // timebase of the the syncronized CAN bus clock.
211 int64_t GetTimestamp() {
212 std::chrono::nanoseconds latest_timestamp =
213 torque_current_.GetTimestamp().GetTime();
214
215 return latest_timestamp.count();
216 }
217
218 void RefreshNontimesyncedSignals() { device_temp_.Refresh(); };
219
220 private:
221 ctre::phoenix6::hardware::TalonFX talon_;
222 int device_id_;
223
224 ctre::phoenix6::signals::InvertedValue inverted_;
225
226 ctre::phoenix6::StatusSignal<units::temperature::celsius_t> device_temp_;
227 ctre::phoenix6::StatusSignal<units::voltage::volt_t> supply_voltage_;
228 ctre::phoenix6::StatusSignal<units::current::ampere_t> supply_current_,
229 torque_current_;
230 ctre::phoenix6::StatusSignal<units::angle::turn_t> position_;
231 ctre::phoenix6::StatusSignal<units::dimensionless::scalar_t> duty_cycle_;
232};
233
234class CANSensorReader {
235 public:
236 CANSensorReader(
237 aos::EventLoop *event_loop,
238 std::vector<ctre::phoenix6::BaseStatusSignal *> signals_registry)
239 : event_loop_(event_loop),
240 signals_(signals_registry.begin(), signals_registry.end()),
241 can_position_sender_(
242 event_loop
243 ->MakeSender<frc971::control_loops::drivetrain::CANPosition>(
Maxwell Henderson4d4be542023-11-29 18:26:13 -0800244 "/drivetrain")) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700245 event_loop->SetRuntimeRealtimePriority(40);
246 event_loop->SetRuntimeAffinity(aos::MakeCpusetFromCpus({1}));
247 timer_handler_ = event_loop->AddTimer([this]() { Loop(); });
248 timer_handler_->set_name("CANSensorReader Loop");
249
250 event_loop->OnRun([this]() {
251 timer_handler_->Schedule(event_loop_->monotonic_now(),
252 1 / kCANUpdateFreqHz);
253 });
254 }
255
256 void set_falcons(std::shared_ptr<Falcon> right_front,
Maxwell Henderson9033d712024-01-07 13:05:36 -0800257 std::shared_ptr<Falcon> right_back) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700258 right_front_ = std::move(right_front);
259 right_back_ = std::move(right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700260 }
261
262 private:
263 void Loop() {
264 ctre::phoenix::StatusCode status =
265 ctre::phoenix6::BaseStatusSignal::WaitForAll(2000_ms, signals_);
266
267 if (!status.IsOK()) {
268 AOS_LOG(ERROR, "Failed to read signals from falcons: %s: %s",
269 status.GetName(), status.GetDescription());
270 }
271
272 auto builder = can_position_sender_.MakeBuilder();
273
Maxwell Henderson9033d712024-01-07 13:05:36 -0800274 for (auto falcon : {right_front_, right_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700275 falcon->RefreshNontimesyncedSignals();
276 }
277
278 aos::SizedArray<flatbuffers::Offset<frc971::control_loops::CANFalcon>,
279 kCANFalconCount>
280 falcons;
281
Maxwell Henderson9033d712024-01-07 13:05:36 -0800282 for (auto falcon : {right_front_, right_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700283 falcons.push_back(falcon->WritePosition(builder.fbb()));
284 }
285
286 auto falcons_list =
287 builder.fbb()
288 ->CreateVector<
289 flatbuffers::Offset<frc971::control_loops::CANFalcon>>(falcons);
290
291 frc971::control_loops::drivetrain::CANPosition::Builder
292 can_position_builder =
293 builder
294 .MakeBuilder<frc971::control_loops::drivetrain::CANPosition>();
295
296 can_position_builder.add_falcons(falcons_list);
297 can_position_builder.add_timestamp(right_front_->GetTimestamp());
298 can_position_builder.add_status(static_cast<int>(status));
299
300 builder.CheckOk(builder.Send(can_position_builder.Finish()));
301 }
302
303 aos::EventLoop *event_loop_;
304
305 const std::vector<ctre::phoenix6::BaseStatusSignal *> signals_;
306 aos::Sender<frc971::control_loops::drivetrain::CANPosition>
307 can_position_sender_;
308
Maxwell Henderson9033d712024-01-07 13:05:36 -0800309 std::shared_ptr<Falcon> right_front_, right_back_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700310
311 // Pointer to the timer handler used to modify the wakeup.
312 ::aos::TimerHandler *timer_handler_;
313};
314
315// Class to send position messages with sensor readings to our loops.
316class SensorReader : public ::frc971::wpilib::SensorReader {
317 public:
318 SensorReader(::aos::ShmEventLoop *event_loop,
319 std::shared_ptr<const Values> values,
320 CANSensorReader *can_sensor_reader)
321 : ::frc971::wpilib::SensorReader(event_loop),
322 values_(std::move(values)),
323 auto_mode_sender_(
324 event_loop->MakeSender<::frc971::autonomous::AutonomousMode>(
325 "/autonomous")),
326 superstructure_position_sender_(
327 event_loop->MakeSender<superstructure::Position>(
328 "/superstructure")),
329 drivetrain_position_sender_(
330 event_loop
331 ->MakeSender<::frc971::control_loops::drivetrain::Position>(
332 "/drivetrain")),
333 gyro_sender_(event_loop->MakeSender<::frc971::sensors::GyroReading>(
334 "/drivetrain")),
335 can_sensor_reader_(can_sensor_reader) {
336 // Set to filter out anything shorter than 1/4 of the minimum pulse width
337 // we should ever see.
338 UpdateFastEncoderFilterHz(kMaxFastEncoderPulsesPerSecond);
339 event_loop->SetRuntimeAffinity(aos::MakeCpusetFromCpus({0}));
340 }
341
342 void Start() override { AddToDMA(&imu_yaw_rate_reader_); }
343
344 // Auto mode switches.
345 void set_autonomous_mode(int i, ::std::unique_ptr<frc::DigitalInput> sensor) {
346 autonomous_modes_.at(i) = ::std::move(sensor);
347 }
348
349 void set_yaw_rate_input(::std::unique_ptr<frc::DigitalInput> sensor) {
350 imu_yaw_rate_input_ = ::std::move(sensor);
351 imu_yaw_rate_reader_.set_input(imu_yaw_rate_input_.get());
352 }
353
354 void RunIteration() override {
355 superstructure_reading_->Set(true);
Ariv Diggic892e922023-10-21 15:52:06 -0700356 {
357 auto builder = superstructure_position_sender_.MakeBuilder();
358
Ariv Diggic892e922023-10-21 15:52:06 -0700359 superstructure::Position::Builder position_builder =
360 builder.MakeBuilder<superstructure::Position>();
Ariv Diggic892e922023-10-21 15:52:06 -0700361 builder.CheckOk(builder.Send(position_builder.Finish()));
362 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700363
364 {
365 auto builder = drivetrain_position_sender_.MakeBuilder();
366 frc971::control_loops::drivetrain::Position::Builder drivetrain_builder =
367 builder.MakeBuilder<frc971::control_loops::drivetrain::Position>();
368 drivetrain_builder.add_left_encoder(
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800369 -constants::Values::DrivetrainEncoderToMeters(
Ariv Diggi0af59c02023-10-07 13:15:39 -0700370 drivetrain_left_encoder_->GetRaw()));
371 drivetrain_builder.add_left_speed(
372 drivetrain_velocity_translate(drivetrain_left_encoder_->GetPeriod()));
373
374 drivetrain_builder.add_right_encoder(
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800375 constants::Values::DrivetrainEncoderToMeters(
Ariv Diggi0af59c02023-10-07 13:15:39 -0700376 drivetrain_right_encoder_->GetRaw()));
377 drivetrain_builder.add_right_speed(-drivetrain_velocity_translate(
378 drivetrain_right_encoder_->GetPeriod()));
379
380 builder.CheckOk(builder.Send(drivetrain_builder.Finish()));
381 }
382
383 {
384 auto builder = gyro_sender_.MakeBuilder();
385 ::frc971::sensors::GyroReading::Builder gyro_reading_builder =
386 builder.MakeBuilder<::frc971::sensors::GyroReading>();
387 // +/- 2000 deg / sec
388 constexpr double kMaxVelocity = 4000; // degrees / second
389 constexpr double kVelocityRadiansPerSecond =
390 kMaxVelocity / 360 * (2.0 * M_PI);
391
392 // Only part of the full range is used to prevent being 100% on or off.
393 constexpr double kScaledRangeLow = 0.1;
394 constexpr double kScaledRangeHigh = 0.9;
395
396 constexpr double kPWMFrequencyHz = 200;
397 double velocity_duty_cycle =
398 imu_yaw_rate_reader_.last_width() * kPWMFrequencyHz;
399
400 constexpr double kDutyCycleScale =
401 1 / (kScaledRangeHigh - kScaledRangeLow);
402 // scale from 0.1 - 0.9 to 0 - 1
403 double rescaled_velocity_duty_cycle =
404 (velocity_duty_cycle - kScaledRangeLow) * kDutyCycleScale;
405
406 if (!std::isnan(rescaled_velocity_duty_cycle)) {
407 gyro_reading_builder.add_velocity((rescaled_velocity_duty_cycle - 0.5) *
408 kVelocityRadiansPerSecond);
409 }
410 builder.CheckOk(builder.Send(gyro_reading_builder.Finish()));
411 }
412
413 {
414 auto builder = auto_mode_sender_.MakeBuilder();
415
416 uint32_t mode = 0;
417 for (size_t i = 0; i < autonomous_modes_.size(); ++i) {
418 if (autonomous_modes_[i] && autonomous_modes_[i]->Get()) {
419 mode |= 1 << i;
420 }
421 }
422
423 auto auto_mode_builder =
424 builder.MakeBuilder<frc971::autonomous::AutonomousMode>();
425
426 auto_mode_builder.add_mode(mode);
427
428 builder.CheckOk(builder.Send(auto_mode_builder.Finish()));
429 }
430 }
431
432 std::shared_ptr<frc::DigitalOutput> superstructure_reading_;
433
434 void set_superstructure_reading(
435 std::shared_ptr<frc::DigitalOutput> superstructure_reading) {
436 superstructure_reading_ = superstructure_reading;
437 }
438
439 private:
440 std::shared_ptr<const Values> values_;
441
442 aos::Sender<frc971::autonomous::AutonomousMode> auto_mode_sender_;
443 aos::Sender<superstructure::Position> superstructure_position_sender_;
444 aos::Sender<frc971::control_loops::drivetrain::Position>
445 drivetrain_position_sender_;
446 ::aos::Sender<::frc971::sensors::GyroReading> gyro_sender_;
447
448 std::array<std::unique_ptr<frc::DigitalInput>, 2> autonomous_modes_;
449
Maxwell Henderson4d4be542023-11-29 18:26:13 -0800450 std::unique_ptr<frc::DigitalInput> imu_yaw_rate_input_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700451
452 frc971::wpilib::DMAPulseWidthReader imu_yaw_rate_reader_;
453
454 CANSensorReader *can_sensor_reader_;
455};
Ariv Diggi0af59c02023-10-07 13:15:39 -0700456class DrivetrainWriter : public ::frc971::wpilib::LoopOutputHandler<
457 ::frc971::control_loops::drivetrain::Output> {
458 public:
459 DrivetrainWriter(::aos::EventLoop *event_loop)
460 : ::frc971::wpilib::LoopOutputHandler<
461 ::frc971::control_loops::drivetrain::Output>(event_loop,
462 "/drivetrain") {
463 event_loop->SetRuntimeRealtimePriority(
464 constants::Values::kDrivetrainWriterPriority);
465
466 event_loop->OnRun([this]() { WriteConfigs(); });
467 }
468
469 void set_falcons(std::shared_ptr<Falcon> right_front,
Maxwell Henderson9033d712024-01-07 13:05:36 -0800470 std::shared_ptr<Falcon> right_back) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700471 right_front_ = std::move(right_front);
472 right_back_ = std::move(right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700473 }
474
475 void set_right_inverted(ctre::phoenix6::signals::InvertedValue invert) {
476 right_inverted_ = invert;
477 }
478
Ariv Diggi0af59c02023-10-07 13:15:39 -0700479 void HandleCANConfiguration(const frc971::CANConfiguration &configuration) {
Maxwell Henderson9033d712024-01-07 13:05:36 -0800480 for (auto falcon : {right_front_, right_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700481 falcon->PrintConfigs();
482 }
483 if (configuration.reapply()) {
484 WriteConfigs();
485 }
486 }
487
488 private:
489 void WriteConfigs() {
Mirabel Wangf4e42672023-10-14 13:12:49 -0700490 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700491 falcon->WriteConfigs(right_inverted_);
492 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700493 }
494
495 void Write(
496 const ::frc971::control_loops::drivetrain::Output &output) override {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700497 ctre::phoenix6::controls::DutyCycleOut right_control(
498 SafeSpeed(output.right_voltage()));
499 right_control.UpdateFreqHz = 0_Hz;
500 right_control.EnableFOC = true;
501
Mirabel Wangf4e42672023-10-14 13:12:49 -0700502 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700503 ctre::phoenix::StatusCode status =
504 falcon->talon()->SetControl(right_control);
505
506 if (!status.IsOK()) {
507 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
508 status.GetName(), status.GetDescription());
509 }
510 }
511 }
512
513 void Stop() override {
514 AOS_LOG(WARNING, "drivetrain output too old\n");
515 ctre::phoenix6::controls::DutyCycleOut stop_command(0.0);
516 stop_command.UpdateFreqHz = 0_Hz;
517 stop_command.EnableFOC = true;
518
Maxwell Henderson9033d712024-01-07 13:05:36 -0800519 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700520 falcon->talon()->SetControl(stop_command);
521 }
522 }
523
524 double SafeSpeed(double voltage) {
525 return (::aos::Clip(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
526 }
527
Maxwell Henderson9033d712024-01-07 13:05:36 -0800528 ctre::phoenix6::signals::InvertedValue right_inverted_;
529 std::shared_ptr<Falcon> right_front_, right_back_;
530};
531class PWMDrivetrainWriter : public ::frc971::wpilib::LoopOutputHandler<
532 ::frc971::control_loops::drivetrain::Output> {
533 public:
534 static constexpr double kMaxBringupPower = 12.0;
535
536 PWMDrivetrainWriter(::aos::EventLoop *event_loop)
537 : ::frc971::wpilib::LoopOutputHandler<
538 ::frc971::control_loops::drivetrain::Output>(event_loop,
539 "/drivetrain") {}
540
541 void set_left_controller0(::std::unique_ptr<::frc::PWM> t, bool reversed) {
542 left_controller0_ = ::std::move(t);
543 reversed_left0_ = reversed;
544 }
545
546 void set_left_controller1(::std::unique_ptr<::frc::PWM> t, bool reversed) {
547 left_controller1_ = ::std::move(t);
548 reversed_left1_ = reversed;
549 }
550
551 private:
552 void Write(
553 const ::frc971::control_loops::drivetrain::Output &output) override {
554 left_controller0_->SetSpeed(
555 SafeSpeed(reversed_left0_, output.left_voltage()));
556
557 if (left_controller1_) {
558 left_controller1_->SetSpeed(
559 SafeSpeed(reversed_left1_, output.left_voltage()));
560 }
561 }
562 void Stop() override {
563 AOS_LOG(WARNING, "drivetrain output too old\n");
564 left_controller0_->SetDisabled();
565
566 if (left_controller1_) {
567 left_controller1_->SetDisabled();
568 }
569 }
570
571 double SafeSpeed(bool reversed, double voltage) {
572 return (::aos::Clip((reversed ? -1.0 : 1.0) * voltage, -kMaxBringupPower,
573 kMaxBringupPower) /
574 12.0);
575 }
576
577 ::std::unique_ptr<::frc::PWM> left_controller0_, left_controller1_;
578
579 bool reversed_right0_, reversed_left0_, reversed_right1_, reversed_left1_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700580};
581
582class WPILibRobot : public ::frc971::wpilib::WPILibRobotBase {
583 public:
584 ::std::unique_ptr<frc::Encoder> make_encoder(int index) {
585 return make_unique<frc::Encoder>(10 + index * 2, 11 + index * 2, false,
586 frc::Encoder::k4X);
587 }
588
589 void Run() override {
590 std::shared_ptr<const Values> values =
591 std::make_shared<const Values>(constants::MakeValues());
592
593 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
594 aos::configuration::ReadConfig("aos_config.json");
595
596 // Thread 1.
597 ::aos::ShmEventLoop joystick_sender_event_loop(&config.message());
598 ::frc971::wpilib::JoystickSender joystick_sender(
599 &joystick_sender_event_loop);
600 AddLoop(&joystick_sender_event_loop);
601
602 // Thread 2.
603 ::aos::ShmEventLoop pdp_fetcher_event_loop(&config.message());
604 ::frc971::wpilib::PDPFetcher pdp_fetcher(&pdp_fetcher_event_loop);
605 AddLoop(&pdp_fetcher_event_loop);
606
607 std::shared_ptr<frc::DigitalOutput> superstructure_reading =
608 make_unique<frc::DigitalOutput>(25);
609
610 std::vector<ctre::phoenix6::BaseStatusSignal *> signals_registry;
611 std::shared_ptr<Falcon> right_front =
612 std::make_shared<Falcon>(1, "Drivetrain Bus", &signals_registry);
613 std::shared_ptr<Falcon> right_back =
Maxwell Henderson3772d282023-11-06 11:07:49 -0800614 std::make_shared<Falcon>(0, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700615
616 // Thread 3.
Maxwell Henderson9033d712024-01-07 13:05:36 -0800617 ::aos::ShmEventLoop output_event_loop(&config.message());
618 PWMDrivetrainWriter drivetrain_writer(&output_event_loop);
619 drivetrain_writer.set_left_controller0(
620 ::std::unique_ptr<::frc::VictorSP>(new ::frc::VictorSP(0)), true);
621
622 AddLoop(&output_event_loop);
623
624 // Thread 4
Ariv Diggi0af59c02023-10-07 13:15:39 -0700625 ::aos::ShmEventLoop can_sensor_reader_event_loop(&config.message());
626 can_sensor_reader_event_loop.set_name("CANSensorReader");
627 CANSensorReader can_sensor_reader(&can_sensor_reader_event_loop,
628 std::move(signals_registry));
Maxwell Henderson9033d712024-01-07 13:05:36 -0800629 can_sensor_reader.set_falcons(right_front, right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700630 AddLoop(&can_sensor_reader_event_loop);
631
Maxwell Henderson9033d712024-01-07 13:05:36 -0800632 // Thread 5.
Ariv Diggi0af59c02023-10-07 13:15:39 -0700633 ::aos::ShmEventLoop sensor_reader_event_loop(&config.message());
634 SensorReader sensor_reader(&sensor_reader_event_loop, values,
635 &can_sensor_reader);
636 sensor_reader.set_pwm_trigger(true);
Maxwell Henderson9033d712024-01-07 13:05:36 -0800637 sensor_reader.set_drivetrain_left_encoder(make_encoder(1));
638 sensor_reader.set_drivetrain_right_encoder(make_encoder(0));
Ariv Diggi0af59c02023-10-07 13:15:39 -0700639 sensor_reader.set_superstructure_reading(superstructure_reading);
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800640 sensor_reader.set_yaw_rate_input(make_unique<frc::DigitalInput>(3));
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800641
Ariv Diggi0af59c02023-10-07 13:15:39 -0700642 AddLoop(&sensor_reader_event_loop);
643
Maxwell Henderson9033d712024-01-07 13:05:36 -0800644 // Thread 6.
Ariv Diggi0af59c02023-10-07 13:15:39 -0700645 // Set up CAN.
646 if (!FLAGS_ctre_diag_server) {
647 c_Phoenix_Diagnostics_SetSecondsToStart(-1);
648 c_Phoenix_Diagnostics_Dispose();
649 }
650
651 ctre::phoenix::platform::can::CANComm_SetRxSchedPriority(
652 constants::Values::kDrivetrainRxPriority, true, "Drivetrain Bus");
653 ctre::phoenix::platform::can::CANComm_SetTxSchedPriority(
654 constants::Values::kDrivetrainTxPriority, true, "Drivetrain Bus");
655
656 ::aos::ShmEventLoop can_output_event_loop(&config.message());
657 can_output_event_loop.set_name("CANOutputWriter");
Maxwell Henderson9033d712024-01-07 13:05:36 -0800658 DrivetrainWriter can_drivetrain_writer(&can_output_event_loop);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700659
Maxwell Henderson9033d712024-01-07 13:05:36 -0800660 can_drivetrain_writer.set_falcons(right_front, right_back);
661 can_drivetrain_writer.set_right_inverted(
Ariv Diggi0af59c02023-10-07 13:15:39 -0700662 ctre::phoenix6::signals::InvertedValue::CounterClockwise_Positive);
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800663
Ariv Diggi0af59c02023-10-07 13:15:39 -0700664 can_output_event_loop.MakeWatcher(
Maxwell Henderson9033d712024-01-07 13:05:36 -0800665 "/roborio", [&can_drivetrain_writer](
666 const frc971::CANConfiguration &configuration) {
667 can_drivetrain_writer.HandleCANConfiguration(configuration);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700668 });
669
670 AddLoop(&can_output_event_loop);
671
Ariv Diggi0af59c02023-10-07 13:15:39 -0700672 RunLoops();
673 }
674};
675
676} // namespace wpilib
677} // namespace y2023_bot3
678
Maxwell Henderson1c0843c2023-12-22 16:20:59 -0800679AOS_ROBOT_CLASS(::y2023_bot3::wpilib::WPILibRobot);