blob: 2b5a9f47d54f169b2cdde3852e143ddd1679fed7 [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"
27#include "ctre/phoenix/motorcontrol/can/TalonFX.h"
28#include "ctre/phoenix/motorcontrol/can/TalonSRX.h"
29#include "ctre/phoenix6/TalonFX.hpp"
30
31#include "aos/commonmath.h"
32#include "aos/containers/sized_array.h"
33#include "aos/events/event_loop.h"
34#include "aos/events/shm_event_loop.h"
35#include "aos/init.h"
36#include "aos/logging/logging.h"
37#include "aos/realtime.h"
38#include "aos/time/time.h"
39#include "aos/util/log_interval.h"
40#include "aos/util/phased_loop.h"
41#include "aos/util/wrapping_counter.h"
42#include "frc971/autonomous/auto_mode_generated.h"
43#include "frc971/can_configuration_generated.h"
44#include "frc971/control_loops/drivetrain/drivetrain_can_position_generated.h"
45#include "frc971/control_loops/drivetrain/drivetrain_position_generated.h"
46#include "frc971/input/robot_state_generated.h"
47#include "frc971/queues/gyro_generated.h"
48#include "frc971/wpilib/ADIS16448.h"
49#include "frc971/wpilib/buffered_pcm.h"
50#include "frc971/wpilib/buffered_solenoid.h"
51#include "frc971/wpilib/dma.h"
52#include "frc971/wpilib/drivetrain_writer.h"
53#include "frc971/wpilib/encoder_and_potentiometer.h"
54#include "frc971/wpilib/joystick_sender.h"
55#include "frc971/wpilib/logging_generated.h"
56#include "frc971/wpilib/loop_output_handler.h"
57#include "frc971/wpilib/pdp_fetcher.h"
58#include "frc971/wpilib/sensor_reader.h"
59#include "frc971/wpilib/wpilib_robot_base.h"
60#include "y2023_bot3/constants.h"
61#include "y2023_bot3/control_loops/superstructure/led_indicator.h"
62#include "y2023_bot3/control_loops/superstructure/superstructure_output_generated.h"
63#include "y2023_bot3/control_loops/superstructure/superstructure_position_generated.h"
64
65DEFINE_bool(ctre_diag_server, false,
66 "If true, enable the diagnostics server for interacting with "
67 "devices on the CAN bus using Phoenix Tuner");
68
69using ::aos::monotonic_clock;
70using ::y2023_bot3::constants::Values;
71namespace superstructure = ::y2023_bot3::control_loops::superstructure;
72namespace drivetrain = ::y2023_bot3::control_loops::drivetrain;
73namespace chrono = ::std::chrono;
74using std::make_unique;
75
76namespace y2023_bot3 {
77namespace wpilib {
78namespace {
79
80constexpr double kMaxBringupPower = 12.0;
81
82// TODO(Brian): Fix the interpretation of the result of GetRaw here and in the
83// DMA stuff and then removing the * 2.0 in *_translate.
84// The low bit is direction.
85
86double drivetrain_velocity_translate(double in) {
87 return (((1.0 / in) / Values::kDrivetrainCyclesPerRevolution()) *
88 (2.0 * M_PI)) *
89 Values::kDrivetrainEncoderRatio() *
90 control_loops::drivetrain::kWheelRadius;
91}
92
93constexpr double kMaxFastEncoderPulsesPerSecond = std::max({
94 Values::kMaxDrivetrainEncoderPulsesPerSecond(),
95});
96static_assert(kMaxFastEncoderPulsesPerSecond <= 1300000,
97 "fast encoders are too fast");
98
99} // namespace
100
101static constexpr int kCANFalconCount = 6;
102static constexpr units::frequency::hertz_t kCANUpdateFreqHz = 200_Hz;
103
104class Falcon {
105 public:
106 Falcon(int device_id, std::string canbus,
107 std::vector<ctre::phoenix6::BaseStatusSignal *> *signals)
108 : talon_(device_id, canbus),
109 device_id_(device_id),
110 device_temp_(talon_.GetDeviceTemp()),
111 supply_voltage_(talon_.GetSupplyVoltage()),
112 supply_current_(talon_.GetSupplyCurrent()),
113 torque_current_(talon_.GetTorqueCurrent()),
114 position_(talon_.GetPosition()),
115 duty_cycle_(talon_.GetDutyCycle()) {
116 // device temp is not timesynced so don't add it to the list of signals
117 device_temp_.SetUpdateFrequency(kCANUpdateFreqHz);
118
119 CHECK_NOTNULL(signals);
120
121 supply_voltage_.SetUpdateFrequency(kCANUpdateFreqHz);
122 signals->push_back(&supply_voltage_);
123
124 supply_current_.SetUpdateFrequency(kCANUpdateFreqHz);
125 signals->push_back(&supply_current_);
126
127 torque_current_.SetUpdateFrequency(kCANUpdateFreqHz);
128 signals->push_back(&torque_current_);
129
130 position_.SetUpdateFrequency(kCANUpdateFreqHz);
131 signals->push_back(&position_);
132
133 duty_cycle_.SetUpdateFrequency(kCANUpdateFreqHz);
134 signals->push_back(&duty_cycle_);
135 }
136
137 void PrintConfigs() {
138 ctre::phoenix6::configs::TalonFXConfiguration configuration;
139 ctre::phoenix::StatusCode status =
140 talon_.GetConfigurator().Refresh(configuration);
141 if (!status.IsOK()) {
142 AOS_LOG(ERROR, "Failed to get falcon configuration: %s: %s",
143 status.GetName(), status.GetDescription());
144 }
145 AOS_LOG(INFO, "configuration: %s", configuration.ToString().c_str());
146 }
147
148 void WriteConfigs(ctre::phoenix6::signals::InvertedValue invert) {
149 inverted_ = invert;
150
151 ctre::phoenix6::configs::CurrentLimitsConfigs current_limits;
152 current_limits.StatorCurrentLimit =
153 constants::Values::kDrivetrainStatorCurrentLimit();
154 current_limits.StatorCurrentLimitEnable = true;
155 current_limits.SupplyCurrentLimit =
156 constants::Values::kDrivetrainSupplyCurrentLimit();
157 current_limits.SupplyCurrentLimitEnable = true;
158
159 ctre::phoenix6::configs::MotorOutputConfigs output_configs;
160 output_configs.NeutralMode =
161 ctre::phoenix6::signals::NeutralModeValue::Brake;
162 output_configs.DutyCycleNeutralDeadband = 0;
163
164 output_configs.Inverted = inverted_;
165
166 ctre::phoenix6::configs::TalonFXConfiguration configuration;
167 configuration.CurrentLimits = current_limits;
168 configuration.MotorOutput = output_configs;
169
170 ctre::phoenix::StatusCode status =
171 talon_.GetConfigurator().Apply(configuration);
172 if (!status.IsOK()) {
173 AOS_LOG(ERROR, "Failed to set falcon configuration: %s: %s",
174 status.GetName(), status.GetDescription());
175 }
176
177 PrintConfigs();
178 }
179
180 ctre::phoenix6::hardware::TalonFX *talon() { return &talon_; }
181
182 flatbuffers::Offset<frc971::control_loops::CANFalcon> WritePosition(
183 flatbuffers::FlatBufferBuilder *fbb) {
184 frc971::control_loops::CANFalcon::Builder builder(*fbb);
185 builder.add_id(device_id_);
186 builder.add_device_temp(device_temp());
187 builder.add_supply_voltage(supply_voltage());
188 builder.add_supply_current(supply_current());
189 builder.add_torque_current(torque_current());
190 builder.add_duty_cycle(duty_cycle());
191
192 double invert =
193 (inverted_ == ctre::phoenix6::signals::InvertedValue::Clockwise_Positive
194 ? 1
195 : -1);
196
197 builder.add_position(
198 constants::Values::DrivetrainCANEncoderToMeters(position()) * invert);
199
200 return builder.Finish();
201 }
202
203 int device_id() const { return device_id_; }
204 float device_temp() const { return device_temp_.GetValue().value(); }
205 float supply_voltage() const { return supply_voltage_.GetValue().value(); }
206 float supply_current() const { return supply_current_.GetValue().value(); }
207 float torque_current() const { return torque_current_.GetValue().value(); }
208 float duty_cycle() const { return duty_cycle_.GetValue().value(); }
209 float position() const { return position_.GetValue().value(); }
210
211 // returns the monotonic timestamp of the latest timesynced reading in the
212 // timebase of the the syncronized CAN bus clock.
213 int64_t GetTimestamp() {
214 std::chrono::nanoseconds latest_timestamp =
215 torque_current_.GetTimestamp().GetTime();
216
217 return latest_timestamp.count();
218 }
219
220 void RefreshNontimesyncedSignals() { device_temp_.Refresh(); };
221
222 private:
223 ctre::phoenix6::hardware::TalonFX talon_;
224 int device_id_;
225
226 ctre::phoenix6::signals::InvertedValue inverted_;
227
228 ctre::phoenix6::StatusSignal<units::temperature::celsius_t> device_temp_;
229 ctre::phoenix6::StatusSignal<units::voltage::volt_t> supply_voltage_;
230 ctre::phoenix6::StatusSignal<units::current::ampere_t> supply_current_,
231 torque_current_;
232 ctre::phoenix6::StatusSignal<units::angle::turn_t> position_;
233 ctre::phoenix6::StatusSignal<units::dimensionless::scalar_t> duty_cycle_;
234};
235
236class CANSensorReader {
237 public:
238 CANSensorReader(
239 aos::EventLoop *event_loop,
240 std::vector<ctre::phoenix6::BaseStatusSignal *> signals_registry)
241 : event_loop_(event_loop),
242 signals_(signals_registry.begin(), signals_registry.end()),
243 can_position_sender_(
244 event_loop
245 ->MakeSender<frc971::control_loops::drivetrain::CANPosition>(
246 "/drivetrain")) {
247 event_loop->SetRuntimeRealtimePriority(40);
248 event_loop->SetRuntimeAffinity(aos::MakeCpusetFromCpus({1}));
249 timer_handler_ = event_loop->AddTimer([this]() { Loop(); });
250 timer_handler_->set_name("CANSensorReader Loop");
251
252 event_loop->OnRun([this]() {
253 timer_handler_->Schedule(event_loop_->monotonic_now(),
254 1 / kCANUpdateFreqHz);
255 });
256 }
257
258 void set_falcons(std::shared_ptr<Falcon> right_front,
259 std::shared_ptr<Falcon> right_back,
Ariv Diggi0af59c02023-10-07 13:15:39 -0700260 std::shared_ptr<Falcon> left_front,
Ariv Diggic892e922023-10-21 15:52:06 -0700261 std::shared_ptr<Falcon> left_back,
262 std::shared_ptr<Falcon> roller_falcon) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700263 right_front_ = std::move(right_front);
264 right_back_ = std::move(right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700265 left_front_ = std::move(left_front);
266 left_back_ = std::move(left_back);
Ariv Diggic892e922023-10-21 15:52:06 -0700267 roller_falcon = std::move(roller_falcon);
268 }
269
270 std::optional<frc971::control_loops::CANFalconT> roller_falcon_data() {
271 std::unique_lock<aos::stl_mutex> lock(roller_mutex_);
272 return roller_falcon_data_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700273 }
274
275 private:
276 void Loop() {
277 ctre::phoenix::StatusCode status =
278 ctre::phoenix6::BaseStatusSignal::WaitForAll(2000_ms, signals_);
279
280 if (!status.IsOK()) {
281 AOS_LOG(ERROR, "Failed to read signals from falcons: %s: %s",
282 status.GetName(), status.GetDescription());
283 }
284
285 auto builder = can_position_sender_.MakeBuilder();
286
Mirabel Wangf4e42672023-10-14 13:12:49 -0700287 for (auto falcon : {right_front_, right_back_, left_front_, left_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700288 falcon->RefreshNontimesyncedSignals();
289 }
290
291 aos::SizedArray<flatbuffers::Offset<frc971::control_loops::CANFalcon>,
292 kCANFalconCount>
293 falcons;
294
Mirabel Wangf4e42672023-10-14 13:12:49 -0700295 for (auto falcon : {right_front_, right_back_, left_front_, left_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700296 falcons.push_back(falcon->WritePosition(builder.fbb()));
297 }
298
299 auto falcons_list =
300 builder.fbb()
301 ->CreateVector<
302 flatbuffers::Offset<frc971::control_loops::CANFalcon>>(falcons);
303
304 frc971::control_loops::drivetrain::CANPosition::Builder
305 can_position_builder =
306 builder
307 .MakeBuilder<frc971::control_loops::drivetrain::CANPosition>();
308
309 can_position_builder.add_falcons(falcons_list);
310 can_position_builder.add_timestamp(right_front_->GetTimestamp());
311 can_position_builder.add_status(static_cast<int>(status));
312
313 builder.CheckOk(builder.Send(can_position_builder.Finish()));
314 }
315
316 aos::EventLoop *event_loop_;
317
318 const std::vector<ctre::phoenix6::BaseStatusSignal *> signals_;
319 aos::Sender<frc971::control_loops::drivetrain::CANPosition>
320 can_position_sender_;
321
Ariv Diggic892e922023-10-21 15:52:06 -0700322 std::shared_ptr<Falcon> right_front_, right_back_, left_front_, left_back_,
323 roller_falcon;
324
325 std::optional<frc971::control_loops::CANFalconT> roller_falcon_data_;
326
327 aos::stl_mutex roller_mutex_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700328
329 // Pointer to the timer handler used to modify the wakeup.
330 ::aos::TimerHandler *timer_handler_;
331};
332
333// Class to send position messages with sensor readings to our loops.
334class SensorReader : public ::frc971::wpilib::SensorReader {
335 public:
336 SensorReader(::aos::ShmEventLoop *event_loop,
337 std::shared_ptr<const Values> values,
338 CANSensorReader *can_sensor_reader)
339 : ::frc971::wpilib::SensorReader(event_loop),
340 values_(std::move(values)),
341 auto_mode_sender_(
342 event_loop->MakeSender<::frc971::autonomous::AutonomousMode>(
343 "/autonomous")),
344 superstructure_position_sender_(
345 event_loop->MakeSender<superstructure::Position>(
346 "/superstructure")),
347 drivetrain_position_sender_(
348 event_loop
349 ->MakeSender<::frc971::control_loops::drivetrain::Position>(
350 "/drivetrain")),
351 gyro_sender_(event_loop->MakeSender<::frc971::sensors::GyroReading>(
352 "/drivetrain")),
353 can_sensor_reader_(can_sensor_reader) {
354 // Set to filter out anything shorter than 1/4 of the minimum pulse width
355 // we should ever see.
356 UpdateFastEncoderFilterHz(kMaxFastEncoderPulsesPerSecond);
357 event_loop->SetRuntimeAffinity(aos::MakeCpusetFromCpus({0}));
358 }
359
360 void Start() override { AddToDMA(&imu_yaw_rate_reader_); }
361
362 // Auto mode switches.
363 void set_autonomous_mode(int i, ::std::unique_ptr<frc::DigitalInput> sensor) {
364 autonomous_modes_.at(i) = ::std::move(sensor);
365 }
366
367 void set_yaw_rate_input(::std::unique_ptr<frc::DigitalInput> sensor) {
368 imu_yaw_rate_input_ = ::std::move(sensor);
369 imu_yaw_rate_reader_.set_input(imu_yaw_rate_input_.get());
370 }
371
372 void RunIteration() override {
373 superstructure_reading_->Set(true);
Ariv Diggic892e922023-10-21 15:52:06 -0700374 {
375 auto builder = superstructure_position_sender_.MakeBuilder();
376
377 flatbuffers::Offset<frc971::control_loops::CANFalcon>
378 roller_falcon_offset;
379 auto optional_roller_falcon = can_sensor_reader_->roller_falcon_data();
380 if (optional_roller_falcon.has_value()) {
381 roller_falcon_offset = frc971::control_loops::CANFalcon::Pack(
382 *builder.fbb(), &optional_roller_falcon.value());
383 }
384
385 superstructure::Position::Builder position_builder =
386 builder.MakeBuilder<superstructure::Position>();
387 position_builder.add_end_effector_cube_beam_break(
388 end_effector_cube_beam_break_->Get());
389
390 if (!roller_falcon_offset.IsNull()) {
391 position_builder.add_roller_falcon(roller_falcon_offset);
392 }
393 builder.CheckOk(builder.Send(position_builder.Finish()));
394 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700395
396 {
397 auto builder = drivetrain_position_sender_.MakeBuilder();
398 frc971::control_loops::drivetrain::Position::Builder drivetrain_builder =
399 builder.MakeBuilder<frc971::control_loops::drivetrain::Position>();
400 drivetrain_builder.add_left_encoder(
401 constants::Values::DrivetrainEncoderToMeters(
402 drivetrain_left_encoder_->GetRaw()));
403 drivetrain_builder.add_left_speed(
404 drivetrain_velocity_translate(drivetrain_left_encoder_->GetPeriod()));
405
406 drivetrain_builder.add_right_encoder(
407 -constants::Values::DrivetrainEncoderToMeters(
408 drivetrain_right_encoder_->GetRaw()));
409 drivetrain_builder.add_right_speed(-drivetrain_velocity_translate(
410 drivetrain_right_encoder_->GetPeriod()));
411
412 builder.CheckOk(builder.Send(drivetrain_builder.Finish()));
413 }
414
415 {
416 auto builder = gyro_sender_.MakeBuilder();
417 ::frc971::sensors::GyroReading::Builder gyro_reading_builder =
418 builder.MakeBuilder<::frc971::sensors::GyroReading>();
419 // +/- 2000 deg / sec
420 constexpr double kMaxVelocity = 4000; // degrees / second
421 constexpr double kVelocityRadiansPerSecond =
422 kMaxVelocity / 360 * (2.0 * M_PI);
423
424 // Only part of the full range is used to prevent being 100% on or off.
425 constexpr double kScaledRangeLow = 0.1;
426 constexpr double kScaledRangeHigh = 0.9;
427
428 constexpr double kPWMFrequencyHz = 200;
429 double velocity_duty_cycle =
430 imu_yaw_rate_reader_.last_width() * kPWMFrequencyHz;
431
432 constexpr double kDutyCycleScale =
433 1 / (kScaledRangeHigh - kScaledRangeLow);
434 // scale from 0.1 - 0.9 to 0 - 1
435 double rescaled_velocity_duty_cycle =
436 (velocity_duty_cycle - kScaledRangeLow) * kDutyCycleScale;
437
438 if (!std::isnan(rescaled_velocity_duty_cycle)) {
439 gyro_reading_builder.add_velocity((rescaled_velocity_duty_cycle - 0.5) *
440 kVelocityRadiansPerSecond);
441 }
442 builder.CheckOk(builder.Send(gyro_reading_builder.Finish()));
443 }
444
445 {
446 auto builder = auto_mode_sender_.MakeBuilder();
447
448 uint32_t mode = 0;
449 for (size_t i = 0; i < autonomous_modes_.size(); ++i) {
450 if (autonomous_modes_[i] && autonomous_modes_[i]->Get()) {
451 mode |= 1 << i;
452 }
453 }
454
455 auto auto_mode_builder =
456 builder.MakeBuilder<frc971::autonomous::AutonomousMode>();
457
458 auto_mode_builder.add_mode(mode);
459
460 builder.CheckOk(builder.Send(auto_mode_builder.Finish()));
461 }
462 }
463
464 std::shared_ptr<frc::DigitalOutput> superstructure_reading_;
465
466 void set_superstructure_reading(
467 std::shared_ptr<frc::DigitalOutput> superstructure_reading) {
468 superstructure_reading_ = superstructure_reading;
469 }
470
471 private:
472 std::shared_ptr<const Values> values_;
473
474 aos::Sender<frc971::autonomous::AutonomousMode> auto_mode_sender_;
475 aos::Sender<superstructure::Position> superstructure_position_sender_;
476 aos::Sender<frc971::control_loops::drivetrain::Position>
477 drivetrain_position_sender_;
478 ::aos::Sender<::frc971::sensors::GyroReading> gyro_sender_;
479
480 std::array<std::unique_ptr<frc::DigitalInput>, 2> autonomous_modes_;
481
Ariv Diggic892e922023-10-21 15:52:06 -0700482 std::unique_ptr<frc::DigitalInput> imu_yaw_rate_input_,
483 end_effector_cube_beam_break_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700484
485 frc971::wpilib::DMAPulseWidthReader imu_yaw_rate_reader_;
486
487 CANSensorReader *can_sensor_reader_;
488};
489
490class SuperstructureWriter
491 : public ::frc971::wpilib::LoopOutputHandler<superstructure::Output> {
492 public:
493 SuperstructureWriter(aos::EventLoop *event_loop)
494 : frc971::wpilib::LoopOutputHandler<superstructure::Output>(
495 event_loop, "/superstructure") {
496 event_loop->SetRuntimeRealtimePriority(
497 constants::Values::kDrivetrainWriterPriority);
498 }
499
500 std::shared_ptr<frc::DigitalOutput> superstructure_reading_;
501
502 void set_superstructure_reading(
503 std::shared_ptr<frc::DigitalOutput> superstructure_reading) {
504 superstructure_reading_ = superstructure_reading;
505 }
506
507 private:
508 void Stop() override { AOS_LOG(WARNING, "Superstructure output too old.\n"); }
509
510 void Write(const superstructure::Output &output) override { (void)output; }
511
512 static void WriteCan(const double voltage,
513 ::ctre::phoenix::motorcontrol::can::TalonFX *falcon) {
514 falcon->Set(
515 ctre::phoenix::motorcontrol::ControlMode::PercentOutput,
516 std::clamp(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
517 }
518
519 template <typename T>
520 static void WritePwm(const double voltage, T *motor) {
521 motor->SetSpeed(std::clamp(voltage, -kMaxBringupPower, kMaxBringupPower) /
522 12.0);
523 }
524};
525
526class SuperstructureCANWriter
527 : public ::frc971::wpilib::LoopOutputHandler<superstructure::Output> {
528 public:
529 SuperstructureCANWriter(::aos::EventLoop *event_loop)
530 : ::frc971::wpilib::LoopOutputHandler<superstructure::Output>(
531 event_loop, "/superstructure") {
532 event_loop->SetRuntimeRealtimePriority(
533 constants::Values::kSuperstructureCANWriterPriority);
534
535 event_loop->OnRun([this]() { WriteConfigs(); });
536 };
537
538 void HandleCANConfiguration(const frc971::CANConfiguration &configuration) {
539 if (configuration.reapply()) {
540 WriteConfigs();
541 }
542 }
543
544 private:
545 void WriteConfigs() {}
546
547 void Write(const superstructure::Output &output) override { (void)output; }
548
549 void Stop() override {
550 AOS_LOG(WARNING, "Superstructure CAN output too old.\n");
551 ctre::phoenix6::controls::DutyCycleOut stop_command(0.0);
552 stop_command.UpdateFreqHz = 0_Hz;
553 stop_command.EnableFOC = true;
554 }
555
556 double SafeSpeed(double voltage) {
557 return (::aos::Clip(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
558 }
559};
560
561class DrivetrainWriter : public ::frc971::wpilib::LoopOutputHandler<
562 ::frc971::control_loops::drivetrain::Output> {
563 public:
564 DrivetrainWriter(::aos::EventLoop *event_loop)
565 : ::frc971::wpilib::LoopOutputHandler<
566 ::frc971::control_loops::drivetrain::Output>(event_loop,
567 "/drivetrain") {
568 event_loop->SetRuntimeRealtimePriority(
569 constants::Values::kDrivetrainWriterPriority);
570
571 event_loop->OnRun([this]() { WriteConfigs(); });
572 }
573
574 void set_falcons(std::shared_ptr<Falcon> right_front,
575 std::shared_ptr<Falcon> right_back,
Ariv Diggi0af59c02023-10-07 13:15:39 -0700576 std::shared_ptr<Falcon> left_front,
Mirabel Wangf4e42672023-10-14 13:12:49 -0700577 std::shared_ptr<Falcon> left_back) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700578 right_front_ = std::move(right_front);
579 right_back_ = std::move(right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700580 left_front_ = std::move(left_front);
581 left_back_ = std::move(left_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700582 }
583
584 void set_right_inverted(ctre::phoenix6::signals::InvertedValue invert) {
585 right_inverted_ = invert;
586 }
587
588 void set_left_inverted(ctre::phoenix6::signals::InvertedValue invert) {
589 left_inverted_ = invert;
590 }
591
592 void HandleCANConfiguration(const frc971::CANConfiguration &configuration) {
Mirabel Wangf4e42672023-10-14 13:12:49 -0700593 for (auto falcon : {right_front_, right_back_, left_front_, left_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700594 falcon->PrintConfigs();
595 }
596 if (configuration.reapply()) {
597 WriteConfigs();
598 }
599 }
600
601 private:
602 void WriteConfigs() {
Mirabel Wangf4e42672023-10-14 13:12:49 -0700603 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700604 falcon->WriteConfigs(right_inverted_);
605 }
606
Mirabel Wangf4e42672023-10-14 13:12:49 -0700607 for (auto falcon : {left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700608 falcon->WriteConfigs(left_inverted_);
609 }
610 }
611
612 void Write(
613 const ::frc971::control_loops::drivetrain::Output &output) override {
614 ctre::phoenix6::controls::DutyCycleOut left_control(
615 SafeSpeed(output.left_voltage()));
616 left_control.UpdateFreqHz = 0_Hz;
617 left_control.EnableFOC = true;
618
619 ctre::phoenix6::controls::DutyCycleOut right_control(
620 SafeSpeed(output.right_voltage()));
621 right_control.UpdateFreqHz = 0_Hz;
622 right_control.EnableFOC = true;
623
Mirabel Wangf4e42672023-10-14 13:12:49 -0700624 for (auto falcon : {left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700625 ctre::phoenix::StatusCode status =
626 falcon->talon()->SetControl(left_control);
627
628 if (!status.IsOK()) {
629 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
630 status.GetName(), status.GetDescription());
631 }
632 }
633
Mirabel Wangf4e42672023-10-14 13:12:49 -0700634 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700635 ctre::phoenix::StatusCode status =
636 falcon->talon()->SetControl(right_control);
637
638 if (!status.IsOK()) {
639 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
640 status.GetName(), status.GetDescription());
641 }
642 }
643 }
644
645 void Stop() override {
646 AOS_LOG(WARNING, "drivetrain output too old\n");
647 ctre::phoenix6::controls::DutyCycleOut stop_command(0.0);
648 stop_command.UpdateFreqHz = 0_Hz;
649 stop_command.EnableFOC = true;
650
Mirabel Wangf4e42672023-10-14 13:12:49 -0700651 for (auto falcon : {right_front_.get(), right_back_.get(),
652 left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700653 falcon->talon()->SetControl(stop_command);
654 }
655 }
656
657 double SafeSpeed(double voltage) {
658 return (::aos::Clip(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
659 }
660
661 ctre::phoenix6::signals::InvertedValue left_inverted_, right_inverted_;
Mirabel Wangf4e42672023-10-14 13:12:49 -0700662 std::shared_ptr<Falcon> right_front_, right_back_, left_front_, left_back_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700663};
664
665class WPILibRobot : public ::frc971::wpilib::WPILibRobotBase {
666 public:
667 ::std::unique_ptr<frc::Encoder> make_encoder(int index) {
668 return make_unique<frc::Encoder>(10 + index * 2, 11 + index * 2, false,
669 frc::Encoder::k4X);
670 }
671
672 void Run() override {
673 std::shared_ptr<const Values> values =
674 std::make_shared<const Values>(constants::MakeValues());
675
676 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
677 aos::configuration::ReadConfig("aos_config.json");
678
679 // Thread 1.
680 ::aos::ShmEventLoop joystick_sender_event_loop(&config.message());
681 ::frc971::wpilib::JoystickSender joystick_sender(
682 &joystick_sender_event_loop);
683 AddLoop(&joystick_sender_event_loop);
684
685 // Thread 2.
686 ::aos::ShmEventLoop pdp_fetcher_event_loop(&config.message());
687 ::frc971::wpilib::PDPFetcher pdp_fetcher(&pdp_fetcher_event_loop);
688 AddLoop(&pdp_fetcher_event_loop);
689
690 std::shared_ptr<frc::DigitalOutput> superstructure_reading =
691 make_unique<frc::DigitalOutput>(25);
692
693 std::vector<ctre::phoenix6::BaseStatusSignal *> signals_registry;
694 std::shared_ptr<Falcon> right_front =
695 std::make_shared<Falcon>(1, "Drivetrain Bus", &signals_registry);
696 std::shared_ptr<Falcon> right_back =
697 std::make_shared<Falcon>(2, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700698 std::shared_ptr<Falcon> left_front =
699 std::make_shared<Falcon>(4, "Drivetrain Bus", &signals_registry);
700 std::shared_ptr<Falcon> left_back =
701 std::make_shared<Falcon>(5, "Drivetrain Bus", &signals_registry);
Ariv Diggic892e922023-10-21 15:52:06 -0700702 std::shared_ptr<Falcon> roller_falcon =
703 std::make_shared<Falcon>(13, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700704
705 // Thread 3.
706 ::aos::ShmEventLoop can_sensor_reader_event_loop(&config.message());
707 can_sensor_reader_event_loop.set_name("CANSensorReader");
708 CANSensorReader can_sensor_reader(&can_sensor_reader_event_loop,
709 std::move(signals_registry));
710
Mirabel Wangf4e42672023-10-14 13:12:49 -0700711 can_sensor_reader.set_falcons(right_front, right_back, left_front,
Ariv Diggic892e922023-10-21 15:52:06 -0700712 left_back, roller_falcon);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700713
714 AddLoop(&can_sensor_reader_event_loop);
715
716 // Thread 4.
717 ::aos::ShmEventLoop sensor_reader_event_loop(&config.message());
718 SensorReader sensor_reader(&sensor_reader_event_loop, values,
719 &can_sensor_reader);
720 sensor_reader.set_pwm_trigger(true);
721 sensor_reader.set_drivetrain_left_encoder(make_encoder(1));
722 sensor_reader.set_drivetrain_right_encoder(make_encoder(0));
723 sensor_reader.set_superstructure_reading(superstructure_reading);
724 sensor_reader.set_yaw_rate_input(make_unique<frc::DigitalInput>(0));
725
726 AddLoop(&sensor_reader_event_loop);
727
728 // Thread 5.
729 // Set up CAN.
730 if (!FLAGS_ctre_diag_server) {
731 c_Phoenix_Diagnostics_SetSecondsToStart(-1);
732 c_Phoenix_Diagnostics_Dispose();
733 }
734
735 ctre::phoenix::platform::can::CANComm_SetRxSchedPriority(
736 constants::Values::kDrivetrainRxPriority, true, "Drivetrain Bus");
737 ctre::phoenix::platform::can::CANComm_SetTxSchedPriority(
738 constants::Values::kDrivetrainTxPriority, true, "Drivetrain Bus");
739
740 ::aos::ShmEventLoop can_output_event_loop(&config.message());
741 can_output_event_loop.set_name("CANOutputWriter");
742 DrivetrainWriter drivetrain_writer(&can_output_event_loop);
743
Mirabel Wangf4e42672023-10-14 13:12:49 -0700744 drivetrain_writer.set_falcons(right_front, right_back, left_front,
745 left_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700746 drivetrain_writer.set_right_inverted(
747 ctre::phoenix6::signals::InvertedValue::Clockwise_Positive);
748 drivetrain_writer.set_left_inverted(
749 ctre::phoenix6::signals::InvertedValue::CounterClockwise_Positive);
750
751 can_output_event_loop.MakeWatcher(
752 "/roborio",
753 [&drivetrain_writer](const frc971::CANConfiguration &configuration) {
754 drivetrain_writer.HandleCANConfiguration(configuration);
755 });
756
757 AddLoop(&can_output_event_loop);
758
759 // Thread 6
760 // Set up superstructure output.
761 ::aos::ShmEventLoop output_event_loop(&config.message());
762 output_event_loop.set_name("PWMOutputWriter");
763 SuperstructureWriter superstructure_writer(&output_event_loop);
764
765 superstructure_writer.set_superstructure_reading(superstructure_reading);
766
767 AddLoop(&output_event_loop);
768
769 // Thread 7
770 // Set up led_indicator.
771 ::aos::ShmEventLoop led_indicator_event_loop(&config.message());
772 led_indicator_event_loop.set_name("LedIndicator");
773 control_loops::superstructure::LedIndicator led_indicator(
774 &led_indicator_event_loop);
775 AddLoop(&led_indicator_event_loop);
776
777 RunLoops();
778 }
779};
780
781} // namespace wpilib
782} // namespace y2023_bot3
783
784AOS_ROBOT_CLASS(::y2023_bot3::wpilib::WPILibRobot);