blob: 06fe314bb7589df93ad42c2f3785d1eba84f7b16 [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,
Mirabel Wangf4e42672023-10-14 13:12:49 -0700261 std::shared_ptr<Falcon> left_back) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700262 right_front_ = std::move(right_front);
263 right_back_ = std::move(right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700264 left_front_ = std::move(left_front);
265 left_back_ = std::move(left_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700266 }
267
268 private:
269 void Loop() {
270 ctre::phoenix::StatusCode status =
271 ctre::phoenix6::BaseStatusSignal::WaitForAll(2000_ms, signals_);
272
273 if (!status.IsOK()) {
274 AOS_LOG(ERROR, "Failed to read signals from falcons: %s: %s",
275 status.GetName(), status.GetDescription());
276 }
277
278 auto builder = can_position_sender_.MakeBuilder();
279
Mirabel Wangf4e42672023-10-14 13:12:49 -0700280 for (auto falcon : {right_front_, right_back_, left_front_, left_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700281 falcon->RefreshNontimesyncedSignals();
282 }
283
284 aos::SizedArray<flatbuffers::Offset<frc971::control_loops::CANFalcon>,
285 kCANFalconCount>
286 falcons;
287
Mirabel Wangf4e42672023-10-14 13:12:49 -0700288 for (auto falcon : {right_front_, right_back_, left_front_, left_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700289 falcons.push_back(falcon->WritePosition(builder.fbb()));
290 }
291
292 auto falcons_list =
293 builder.fbb()
294 ->CreateVector<
295 flatbuffers::Offset<frc971::control_loops::CANFalcon>>(falcons);
296
297 frc971::control_loops::drivetrain::CANPosition::Builder
298 can_position_builder =
299 builder
300 .MakeBuilder<frc971::control_loops::drivetrain::CANPosition>();
301
302 can_position_builder.add_falcons(falcons_list);
303 can_position_builder.add_timestamp(right_front_->GetTimestamp());
304 can_position_builder.add_status(static_cast<int>(status));
305
306 builder.CheckOk(builder.Send(can_position_builder.Finish()));
307 }
308
309 aos::EventLoop *event_loop_;
310
311 const std::vector<ctre::phoenix6::BaseStatusSignal *> signals_;
312 aos::Sender<frc971::control_loops::drivetrain::CANPosition>
313 can_position_sender_;
314
Mirabel Wangf4e42672023-10-14 13:12:49 -0700315 std::shared_ptr<Falcon> right_front_, right_back_, left_front_, left_back_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700316
317 // Pointer to the timer handler used to modify the wakeup.
318 ::aos::TimerHandler *timer_handler_;
319};
320
321// Class to send position messages with sensor readings to our loops.
322class SensorReader : public ::frc971::wpilib::SensorReader {
323 public:
324 SensorReader(::aos::ShmEventLoop *event_loop,
325 std::shared_ptr<const Values> values,
326 CANSensorReader *can_sensor_reader)
327 : ::frc971::wpilib::SensorReader(event_loop),
328 values_(std::move(values)),
329 auto_mode_sender_(
330 event_loop->MakeSender<::frc971::autonomous::AutonomousMode>(
331 "/autonomous")),
332 superstructure_position_sender_(
333 event_loop->MakeSender<superstructure::Position>(
334 "/superstructure")),
335 drivetrain_position_sender_(
336 event_loop
337 ->MakeSender<::frc971::control_loops::drivetrain::Position>(
338 "/drivetrain")),
339 gyro_sender_(event_loop->MakeSender<::frc971::sensors::GyroReading>(
340 "/drivetrain")),
341 can_sensor_reader_(can_sensor_reader) {
342 // Set to filter out anything shorter than 1/4 of the minimum pulse width
343 // we should ever see.
344 UpdateFastEncoderFilterHz(kMaxFastEncoderPulsesPerSecond);
345 event_loop->SetRuntimeAffinity(aos::MakeCpusetFromCpus({0}));
346 }
347
348 void Start() override { AddToDMA(&imu_yaw_rate_reader_); }
349
350 // Auto mode switches.
351 void set_autonomous_mode(int i, ::std::unique_ptr<frc::DigitalInput> sensor) {
352 autonomous_modes_.at(i) = ::std::move(sensor);
353 }
354
355 void set_yaw_rate_input(::std::unique_ptr<frc::DigitalInput> sensor) {
356 imu_yaw_rate_input_ = ::std::move(sensor);
357 imu_yaw_rate_reader_.set_input(imu_yaw_rate_input_.get());
358 }
359
360 void RunIteration() override {
361 superstructure_reading_->Set(true);
362
363 {
364 auto builder = drivetrain_position_sender_.MakeBuilder();
365 frc971::control_loops::drivetrain::Position::Builder drivetrain_builder =
366 builder.MakeBuilder<frc971::control_loops::drivetrain::Position>();
367 drivetrain_builder.add_left_encoder(
368 constants::Values::DrivetrainEncoderToMeters(
369 drivetrain_left_encoder_->GetRaw()));
370 drivetrain_builder.add_left_speed(
371 drivetrain_velocity_translate(drivetrain_left_encoder_->GetPeriod()));
372
373 drivetrain_builder.add_right_encoder(
374 -constants::Values::DrivetrainEncoderToMeters(
375 drivetrain_right_encoder_->GetRaw()));
376 drivetrain_builder.add_right_speed(-drivetrain_velocity_translate(
377 drivetrain_right_encoder_->GetPeriod()));
378
379 builder.CheckOk(builder.Send(drivetrain_builder.Finish()));
380 }
381
382 {
383 auto builder = gyro_sender_.MakeBuilder();
384 ::frc971::sensors::GyroReading::Builder gyro_reading_builder =
385 builder.MakeBuilder<::frc971::sensors::GyroReading>();
386 // +/- 2000 deg / sec
387 constexpr double kMaxVelocity = 4000; // degrees / second
388 constexpr double kVelocityRadiansPerSecond =
389 kMaxVelocity / 360 * (2.0 * M_PI);
390
391 // Only part of the full range is used to prevent being 100% on or off.
392 constexpr double kScaledRangeLow = 0.1;
393 constexpr double kScaledRangeHigh = 0.9;
394
395 constexpr double kPWMFrequencyHz = 200;
396 double velocity_duty_cycle =
397 imu_yaw_rate_reader_.last_width() * kPWMFrequencyHz;
398
399 constexpr double kDutyCycleScale =
400 1 / (kScaledRangeHigh - kScaledRangeLow);
401 // scale from 0.1 - 0.9 to 0 - 1
402 double rescaled_velocity_duty_cycle =
403 (velocity_duty_cycle - kScaledRangeLow) * kDutyCycleScale;
404
405 if (!std::isnan(rescaled_velocity_duty_cycle)) {
406 gyro_reading_builder.add_velocity((rescaled_velocity_duty_cycle - 0.5) *
407 kVelocityRadiansPerSecond);
408 }
409 builder.CheckOk(builder.Send(gyro_reading_builder.Finish()));
410 }
411
412 {
413 auto builder = auto_mode_sender_.MakeBuilder();
414
415 uint32_t mode = 0;
416 for (size_t i = 0; i < autonomous_modes_.size(); ++i) {
417 if (autonomous_modes_[i] && autonomous_modes_[i]->Get()) {
418 mode |= 1 << i;
419 }
420 }
421
422 auto auto_mode_builder =
423 builder.MakeBuilder<frc971::autonomous::AutonomousMode>();
424
425 auto_mode_builder.add_mode(mode);
426
427 builder.CheckOk(builder.Send(auto_mode_builder.Finish()));
428 }
429 }
430
431 std::shared_ptr<frc::DigitalOutput> superstructure_reading_;
432
433 void set_superstructure_reading(
434 std::shared_ptr<frc::DigitalOutput> superstructure_reading) {
435 superstructure_reading_ = superstructure_reading;
436 }
437
438 private:
439 std::shared_ptr<const Values> values_;
440
441 aos::Sender<frc971::autonomous::AutonomousMode> auto_mode_sender_;
442 aos::Sender<superstructure::Position> superstructure_position_sender_;
443 aos::Sender<frc971::control_loops::drivetrain::Position>
444 drivetrain_position_sender_;
445 ::aos::Sender<::frc971::sensors::GyroReading> gyro_sender_;
446
447 std::array<std::unique_ptr<frc::DigitalInput>, 2> autonomous_modes_;
448
449 std::unique_ptr<frc::DigitalInput> imu_yaw_rate_input_;
450
451 frc971::wpilib::DMAPulseWidthReader imu_yaw_rate_reader_;
452
453 CANSensorReader *can_sensor_reader_;
454};
455
456class SuperstructureWriter
457 : public ::frc971::wpilib::LoopOutputHandler<superstructure::Output> {
458 public:
459 SuperstructureWriter(aos::EventLoop *event_loop)
460 : frc971::wpilib::LoopOutputHandler<superstructure::Output>(
461 event_loop, "/superstructure") {
462 event_loop->SetRuntimeRealtimePriority(
463 constants::Values::kDrivetrainWriterPriority);
464 }
465
466 std::shared_ptr<frc::DigitalOutput> superstructure_reading_;
467
468 void set_superstructure_reading(
469 std::shared_ptr<frc::DigitalOutput> superstructure_reading) {
470 superstructure_reading_ = superstructure_reading;
471 }
472
473 private:
474 void Stop() override { AOS_LOG(WARNING, "Superstructure output too old.\n"); }
475
476 void Write(const superstructure::Output &output) override { (void)output; }
477
478 static void WriteCan(const double voltage,
479 ::ctre::phoenix::motorcontrol::can::TalonFX *falcon) {
480 falcon->Set(
481 ctre::phoenix::motorcontrol::ControlMode::PercentOutput,
482 std::clamp(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
483 }
484
485 template <typename T>
486 static void WritePwm(const double voltage, T *motor) {
487 motor->SetSpeed(std::clamp(voltage, -kMaxBringupPower, kMaxBringupPower) /
488 12.0);
489 }
490};
491
492class SuperstructureCANWriter
493 : public ::frc971::wpilib::LoopOutputHandler<superstructure::Output> {
494 public:
495 SuperstructureCANWriter(::aos::EventLoop *event_loop)
496 : ::frc971::wpilib::LoopOutputHandler<superstructure::Output>(
497 event_loop, "/superstructure") {
498 event_loop->SetRuntimeRealtimePriority(
499 constants::Values::kSuperstructureCANWriterPriority);
500
501 event_loop->OnRun([this]() { WriteConfigs(); });
502 };
503
504 void HandleCANConfiguration(const frc971::CANConfiguration &configuration) {
505 if (configuration.reapply()) {
506 WriteConfigs();
507 }
508 }
509
510 private:
511 void WriteConfigs() {}
512
513 void Write(const superstructure::Output &output) override { (void)output; }
514
515 void Stop() override {
516 AOS_LOG(WARNING, "Superstructure CAN output too old.\n");
517 ctre::phoenix6::controls::DutyCycleOut stop_command(0.0);
518 stop_command.UpdateFreqHz = 0_Hz;
519 stop_command.EnableFOC = true;
520 }
521
522 double SafeSpeed(double voltage) {
523 return (::aos::Clip(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
524 }
525};
526
527class DrivetrainWriter : public ::frc971::wpilib::LoopOutputHandler<
528 ::frc971::control_loops::drivetrain::Output> {
529 public:
530 DrivetrainWriter(::aos::EventLoop *event_loop)
531 : ::frc971::wpilib::LoopOutputHandler<
532 ::frc971::control_loops::drivetrain::Output>(event_loop,
533 "/drivetrain") {
534 event_loop->SetRuntimeRealtimePriority(
535 constants::Values::kDrivetrainWriterPriority);
536
537 event_loop->OnRun([this]() { WriteConfigs(); });
538 }
539
540 void set_falcons(std::shared_ptr<Falcon> right_front,
541 std::shared_ptr<Falcon> right_back,
Ariv Diggi0af59c02023-10-07 13:15:39 -0700542 std::shared_ptr<Falcon> left_front,
Mirabel Wangf4e42672023-10-14 13:12:49 -0700543 std::shared_ptr<Falcon> left_back) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700544 right_front_ = std::move(right_front);
545 right_back_ = std::move(right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700546 left_front_ = std::move(left_front);
547 left_back_ = std::move(left_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700548 }
549
550 void set_right_inverted(ctre::phoenix6::signals::InvertedValue invert) {
551 right_inverted_ = invert;
552 }
553
554 void set_left_inverted(ctre::phoenix6::signals::InvertedValue invert) {
555 left_inverted_ = invert;
556 }
557
558 void HandleCANConfiguration(const frc971::CANConfiguration &configuration) {
Mirabel Wangf4e42672023-10-14 13:12:49 -0700559 for (auto falcon : {right_front_, right_back_, left_front_, left_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700560 falcon->PrintConfigs();
561 }
562 if (configuration.reapply()) {
563 WriteConfigs();
564 }
565 }
566
567 private:
568 void WriteConfigs() {
Mirabel Wangf4e42672023-10-14 13:12:49 -0700569 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700570 falcon->WriteConfigs(right_inverted_);
571 }
572
Mirabel Wangf4e42672023-10-14 13:12:49 -0700573 for (auto falcon : {left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700574 falcon->WriteConfigs(left_inverted_);
575 }
576 }
577
578 void Write(
579 const ::frc971::control_loops::drivetrain::Output &output) override {
580 ctre::phoenix6::controls::DutyCycleOut left_control(
581 SafeSpeed(output.left_voltage()));
582 left_control.UpdateFreqHz = 0_Hz;
583 left_control.EnableFOC = true;
584
585 ctre::phoenix6::controls::DutyCycleOut right_control(
586 SafeSpeed(output.right_voltage()));
587 right_control.UpdateFreqHz = 0_Hz;
588 right_control.EnableFOC = true;
589
Mirabel Wangf4e42672023-10-14 13:12:49 -0700590 for (auto falcon : {left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700591 ctre::phoenix::StatusCode status =
592 falcon->talon()->SetControl(left_control);
593
594 if (!status.IsOK()) {
595 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
596 status.GetName(), status.GetDescription());
597 }
598 }
599
Mirabel Wangf4e42672023-10-14 13:12:49 -0700600 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700601 ctre::phoenix::StatusCode status =
602 falcon->talon()->SetControl(right_control);
603
604 if (!status.IsOK()) {
605 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
606 status.GetName(), status.GetDescription());
607 }
608 }
609 }
610
611 void Stop() override {
612 AOS_LOG(WARNING, "drivetrain output too old\n");
613 ctre::phoenix6::controls::DutyCycleOut stop_command(0.0);
614 stop_command.UpdateFreqHz = 0_Hz;
615 stop_command.EnableFOC = true;
616
Mirabel Wangf4e42672023-10-14 13:12:49 -0700617 for (auto falcon : {right_front_.get(), right_back_.get(),
618 left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700619 falcon->talon()->SetControl(stop_command);
620 }
621 }
622
623 double SafeSpeed(double voltage) {
624 return (::aos::Clip(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
625 }
626
627 ctre::phoenix6::signals::InvertedValue left_inverted_, right_inverted_;
Mirabel Wangf4e42672023-10-14 13:12:49 -0700628 std::shared_ptr<Falcon> right_front_, right_back_, left_front_, left_back_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700629};
630
631class WPILibRobot : public ::frc971::wpilib::WPILibRobotBase {
632 public:
633 ::std::unique_ptr<frc::Encoder> make_encoder(int index) {
634 return make_unique<frc::Encoder>(10 + index * 2, 11 + index * 2, false,
635 frc::Encoder::k4X);
636 }
637
638 void Run() override {
639 std::shared_ptr<const Values> values =
640 std::make_shared<const Values>(constants::MakeValues());
641
642 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
643 aos::configuration::ReadConfig("aos_config.json");
644
645 // Thread 1.
646 ::aos::ShmEventLoop joystick_sender_event_loop(&config.message());
647 ::frc971::wpilib::JoystickSender joystick_sender(
648 &joystick_sender_event_loop);
649 AddLoop(&joystick_sender_event_loop);
650
651 // Thread 2.
652 ::aos::ShmEventLoop pdp_fetcher_event_loop(&config.message());
653 ::frc971::wpilib::PDPFetcher pdp_fetcher(&pdp_fetcher_event_loop);
654 AddLoop(&pdp_fetcher_event_loop);
655
656 std::shared_ptr<frc::DigitalOutput> superstructure_reading =
657 make_unique<frc::DigitalOutput>(25);
658
659 std::vector<ctre::phoenix6::BaseStatusSignal *> signals_registry;
660 std::shared_ptr<Falcon> right_front =
661 std::make_shared<Falcon>(1, "Drivetrain Bus", &signals_registry);
662 std::shared_ptr<Falcon> right_back =
663 std::make_shared<Falcon>(2, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700664 std::shared_ptr<Falcon> left_front =
665 std::make_shared<Falcon>(4, "Drivetrain Bus", &signals_registry);
666 std::shared_ptr<Falcon> left_back =
667 std::make_shared<Falcon>(5, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700668
669 // Thread 3.
670 ::aos::ShmEventLoop can_sensor_reader_event_loop(&config.message());
671 can_sensor_reader_event_loop.set_name("CANSensorReader");
672 CANSensorReader can_sensor_reader(&can_sensor_reader_event_loop,
673 std::move(signals_registry));
674
Mirabel Wangf4e42672023-10-14 13:12:49 -0700675 can_sensor_reader.set_falcons(right_front, right_back, left_front,
676 left_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700677
678 AddLoop(&can_sensor_reader_event_loop);
679
680 // Thread 4.
681 ::aos::ShmEventLoop sensor_reader_event_loop(&config.message());
682 SensorReader sensor_reader(&sensor_reader_event_loop, values,
683 &can_sensor_reader);
684 sensor_reader.set_pwm_trigger(true);
685 sensor_reader.set_drivetrain_left_encoder(make_encoder(1));
686 sensor_reader.set_drivetrain_right_encoder(make_encoder(0));
687 sensor_reader.set_superstructure_reading(superstructure_reading);
688 sensor_reader.set_yaw_rate_input(make_unique<frc::DigitalInput>(0));
689
690 AddLoop(&sensor_reader_event_loop);
691
692 // Thread 5.
693 // Set up CAN.
694 if (!FLAGS_ctre_diag_server) {
695 c_Phoenix_Diagnostics_SetSecondsToStart(-1);
696 c_Phoenix_Diagnostics_Dispose();
697 }
698
699 ctre::phoenix::platform::can::CANComm_SetRxSchedPriority(
700 constants::Values::kDrivetrainRxPriority, true, "Drivetrain Bus");
701 ctre::phoenix::platform::can::CANComm_SetTxSchedPriority(
702 constants::Values::kDrivetrainTxPriority, true, "Drivetrain Bus");
703
704 ::aos::ShmEventLoop can_output_event_loop(&config.message());
705 can_output_event_loop.set_name("CANOutputWriter");
706 DrivetrainWriter drivetrain_writer(&can_output_event_loop);
707
Mirabel Wangf4e42672023-10-14 13:12:49 -0700708 drivetrain_writer.set_falcons(right_front, right_back, left_front,
709 left_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700710 drivetrain_writer.set_right_inverted(
711 ctre::phoenix6::signals::InvertedValue::Clockwise_Positive);
712 drivetrain_writer.set_left_inverted(
713 ctre::phoenix6::signals::InvertedValue::CounterClockwise_Positive);
714
715 can_output_event_loop.MakeWatcher(
716 "/roborio",
717 [&drivetrain_writer](const frc971::CANConfiguration &configuration) {
718 drivetrain_writer.HandleCANConfiguration(configuration);
719 });
720
721 AddLoop(&can_output_event_loop);
722
723 // Thread 6
724 // Set up superstructure output.
725 ::aos::ShmEventLoop output_event_loop(&config.message());
726 output_event_loop.set_name("PWMOutputWriter");
727 SuperstructureWriter superstructure_writer(&output_event_loop);
728
729 superstructure_writer.set_superstructure_reading(superstructure_reading);
730
731 AddLoop(&output_event_loop);
732
733 // Thread 7
734 // Set up led_indicator.
735 ::aos::ShmEventLoop led_indicator_event_loop(&config.message());
736 led_indicator_event_loop.set_name("LedIndicator");
737 control_loops::superstructure::LedIndicator led_indicator(
738 &led_indicator_event_loop);
739 AddLoop(&led_indicator_event_loop);
740
741 RunLoops();
742 }
743};
744
745} // namespace wpilib
746} // namespace y2023_bot3
747
748AOS_ROBOT_CLASS(::y2023_bot3::wpilib::WPILibRobot);