blob: 09f87dba99787beee22702d7c8ee15a84a863ed4 [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
Maxwell Henderson3772d282023-11-06 11:07:49 -0800180 void WriteRollerConfigs() {
181 ctre::phoenix6::configs::CurrentLimitsConfigs current_limits;
182 current_limits.StatorCurrentLimit =
183 constants::Values::kRollerStatorCurrentLimit();
184 current_limits.StatorCurrentLimitEnable = true;
185 current_limits.SupplyCurrentLimit =
186 constants::Values::kRollerSupplyCurrentLimit();
187 current_limits.SupplyCurrentLimitEnable = true;
188
189 ctre::phoenix6::configs::MotorOutputConfigs output_configs;
190 output_configs.NeutralMode =
191 ctre::phoenix6::signals::NeutralModeValue::Brake;
192 output_configs.DutyCycleNeutralDeadband = 0;
193
194 ctre::phoenix6::configs::TalonFXConfiguration configuration;
195 configuration.CurrentLimits = current_limits;
196 configuration.MotorOutput = output_configs;
197
198 ctre::phoenix::StatusCode status =
199 talon_.GetConfigurator().Apply(configuration);
200 if (!status.IsOK()) {
201 AOS_LOG(ERROR, "Failed to set falcon configuration: %s: %s",
202 status.GetName(), status.GetDescription());
203 }
204
205 PrintConfigs();
206 }
207
Ariv Diggi0af59c02023-10-07 13:15:39 -0700208 ctre::phoenix6::hardware::TalonFX *talon() { return &talon_; }
209
210 flatbuffers::Offset<frc971::control_loops::CANFalcon> WritePosition(
211 flatbuffers::FlatBufferBuilder *fbb) {
212 frc971::control_loops::CANFalcon::Builder builder(*fbb);
213 builder.add_id(device_id_);
214 builder.add_device_temp(device_temp());
215 builder.add_supply_voltage(supply_voltage());
216 builder.add_supply_current(supply_current());
217 builder.add_torque_current(torque_current());
218 builder.add_duty_cycle(duty_cycle());
219
220 double invert =
221 (inverted_ == ctre::phoenix6::signals::InvertedValue::Clockwise_Positive
222 ? 1
223 : -1);
224
225 builder.add_position(
226 constants::Values::DrivetrainCANEncoderToMeters(position()) * invert);
227
228 return builder.Finish();
229 }
230
231 int device_id() const { return device_id_; }
232 float device_temp() const { return device_temp_.GetValue().value(); }
233 float supply_voltage() const { return supply_voltage_.GetValue().value(); }
234 float supply_current() const { return supply_current_.GetValue().value(); }
235 float torque_current() const { return torque_current_.GetValue().value(); }
236 float duty_cycle() const { return duty_cycle_.GetValue().value(); }
237 float position() const { return position_.GetValue().value(); }
238
239 // returns the monotonic timestamp of the latest timesynced reading in the
240 // timebase of the the syncronized CAN bus clock.
241 int64_t GetTimestamp() {
242 std::chrono::nanoseconds latest_timestamp =
243 torque_current_.GetTimestamp().GetTime();
244
245 return latest_timestamp.count();
246 }
247
248 void RefreshNontimesyncedSignals() { device_temp_.Refresh(); };
249
250 private:
251 ctre::phoenix6::hardware::TalonFX talon_;
252 int device_id_;
253
254 ctre::phoenix6::signals::InvertedValue inverted_;
255
256 ctre::phoenix6::StatusSignal<units::temperature::celsius_t> device_temp_;
257 ctre::phoenix6::StatusSignal<units::voltage::volt_t> supply_voltage_;
258 ctre::phoenix6::StatusSignal<units::current::ampere_t> supply_current_,
259 torque_current_;
260 ctre::phoenix6::StatusSignal<units::angle::turn_t> position_;
261 ctre::phoenix6::StatusSignal<units::dimensionless::scalar_t> duty_cycle_;
262};
263
264class CANSensorReader {
265 public:
266 CANSensorReader(
267 aos::EventLoop *event_loop,
268 std::vector<ctre::phoenix6::BaseStatusSignal *> signals_registry)
269 : event_loop_(event_loop),
270 signals_(signals_registry.begin(), signals_registry.end()),
271 can_position_sender_(
272 event_loop
273 ->MakeSender<frc971::control_loops::drivetrain::CANPosition>(
Maxwell Henderson3772d282023-11-06 11:07:49 -0800274 "/drivetrain")),
275 roller_falcon_data_(std::nullopt) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700276 event_loop->SetRuntimeRealtimePriority(40);
277 event_loop->SetRuntimeAffinity(aos::MakeCpusetFromCpus({1}));
278 timer_handler_ = event_loop->AddTimer([this]() { Loop(); });
279 timer_handler_->set_name("CANSensorReader Loop");
280
281 event_loop->OnRun([this]() {
282 timer_handler_->Schedule(event_loop_->monotonic_now(),
283 1 / kCANUpdateFreqHz);
284 });
285 }
286
287 void set_falcons(std::shared_ptr<Falcon> right_front,
288 std::shared_ptr<Falcon> right_back,
Ariv Diggi0af59c02023-10-07 13:15:39 -0700289 std::shared_ptr<Falcon> left_front,
Ariv Diggic892e922023-10-21 15:52:06 -0700290 std::shared_ptr<Falcon> left_back,
291 std::shared_ptr<Falcon> roller_falcon) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700292 right_front_ = std::move(right_front);
293 right_back_ = std::move(right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700294 left_front_ = std::move(left_front);
295 left_back_ = std::move(left_back);
Maxwell Henderson3772d282023-11-06 11:07:49 -0800296 roller_falcon_ = std::move(roller_falcon);
Ariv Diggic892e922023-10-21 15:52:06 -0700297 }
298
299 std::optional<frc971::control_loops::CANFalconT> roller_falcon_data() {
300 std::unique_lock<aos::stl_mutex> lock(roller_mutex_);
301 return roller_falcon_data_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700302 }
303
304 private:
305 void Loop() {
306 ctre::phoenix::StatusCode status =
307 ctre::phoenix6::BaseStatusSignal::WaitForAll(2000_ms, signals_);
308
309 if (!status.IsOK()) {
310 AOS_LOG(ERROR, "Failed to read signals from falcons: %s: %s",
311 status.GetName(), status.GetDescription());
312 }
313
314 auto builder = can_position_sender_.MakeBuilder();
315
Maxwell Henderson3772d282023-11-06 11:07:49 -0800316 for (auto falcon :
317 {right_front_, right_back_, left_front_, left_back_, roller_falcon_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700318 falcon->RefreshNontimesyncedSignals();
319 }
320
321 aos::SizedArray<flatbuffers::Offset<frc971::control_loops::CANFalcon>,
322 kCANFalconCount>
323 falcons;
324
Mirabel Wangf4e42672023-10-14 13:12:49 -0700325 for (auto falcon : {right_front_, right_back_, left_front_, left_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700326 falcons.push_back(falcon->WritePosition(builder.fbb()));
327 }
328
329 auto falcons_list =
330 builder.fbb()
331 ->CreateVector<
332 flatbuffers::Offset<frc971::control_loops::CANFalcon>>(falcons);
333
334 frc971::control_loops::drivetrain::CANPosition::Builder
335 can_position_builder =
336 builder
337 .MakeBuilder<frc971::control_loops::drivetrain::CANPosition>();
338
339 can_position_builder.add_falcons(falcons_list);
340 can_position_builder.add_timestamp(right_front_->GetTimestamp());
341 can_position_builder.add_status(static_cast<int>(status));
342
343 builder.CheckOk(builder.Send(can_position_builder.Finish()));
Maxwell Henderson3772d282023-11-06 11:07:49 -0800344
345 {
346 std::unique_lock<aos::stl_mutex> lock(roller_mutex_);
347 frc971::control_loops::CANFalconT roller_falcon_data;
348 roller_falcon_data.id = roller_falcon_->device_id();
349 roller_falcon_data.supply_current = roller_falcon_->supply_current();
350 roller_falcon_data.torque_current = -roller_falcon_->torque_current();
351 roller_falcon_data.supply_voltage = roller_falcon_->supply_voltage();
352 roller_falcon_data.device_temp = roller_falcon_->device_temp();
353 roller_falcon_data.position = -roller_falcon_->position();
354 roller_falcon_data.duty_cycle = roller_falcon_->duty_cycle();
355 roller_falcon_data_ =
356 std::make_optional<frc971::control_loops::CANFalconT>(
357 roller_falcon_data);
358 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700359 }
360
361 aos::EventLoop *event_loop_;
362
363 const std::vector<ctre::phoenix6::BaseStatusSignal *> signals_;
364 aos::Sender<frc971::control_loops::drivetrain::CANPosition>
365 can_position_sender_;
366
Ariv Diggic892e922023-10-21 15:52:06 -0700367 std::shared_ptr<Falcon> right_front_, right_back_, left_front_, left_back_,
Maxwell Henderson3772d282023-11-06 11:07:49 -0800368 roller_falcon_;
Ariv Diggic892e922023-10-21 15:52:06 -0700369
370 std::optional<frc971::control_loops::CANFalconT> roller_falcon_data_;
371
372 aos::stl_mutex roller_mutex_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700373
374 // Pointer to the timer handler used to modify the wakeup.
375 ::aos::TimerHandler *timer_handler_;
376};
377
378// Class to send position messages with sensor readings to our loops.
379class SensorReader : public ::frc971::wpilib::SensorReader {
380 public:
381 SensorReader(::aos::ShmEventLoop *event_loop,
382 std::shared_ptr<const Values> values,
383 CANSensorReader *can_sensor_reader)
384 : ::frc971::wpilib::SensorReader(event_loop),
385 values_(std::move(values)),
386 auto_mode_sender_(
387 event_loop->MakeSender<::frc971::autonomous::AutonomousMode>(
388 "/autonomous")),
389 superstructure_position_sender_(
390 event_loop->MakeSender<superstructure::Position>(
391 "/superstructure")),
392 drivetrain_position_sender_(
393 event_loop
394 ->MakeSender<::frc971::control_loops::drivetrain::Position>(
395 "/drivetrain")),
396 gyro_sender_(event_loop->MakeSender<::frc971::sensors::GyroReading>(
397 "/drivetrain")),
398 can_sensor_reader_(can_sensor_reader) {
399 // Set to filter out anything shorter than 1/4 of the minimum pulse width
400 // we should ever see.
401 UpdateFastEncoderFilterHz(kMaxFastEncoderPulsesPerSecond);
402 event_loop->SetRuntimeAffinity(aos::MakeCpusetFromCpus({0}));
403 }
404
405 void Start() override { AddToDMA(&imu_yaw_rate_reader_); }
406
407 // Auto mode switches.
408 void set_autonomous_mode(int i, ::std::unique_ptr<frc::DigitalInput> sensor) {
409 autonomous_modes_.at(i) = ::std::move(sensor);
410 }
411
412 void set_yaw_rate_input(::std::unique_ptr<frc::DigitalInput> sensor) {
413 imu_yaw_rate_input_ = ::std::move(sensor);
414 imu_yaw_rate_reader_.set_input(imu_yaw_rate_input_.get());
415 }
416
417 void RunIteration() override {
418 superstructure_reading_->Set(true);
Ariv Diggic892e922023-10-21 15:52:06 -0700419 {
420 auto builder = superstructure_position_sender_.MakeBuilder();
421
422 flatbuffers::Offset<frc971::control_loops::CANFalcon>
423 roller_falcon_offset;
424 auto optional_roller_falcon = can_sensor_reader_->roller_falcon_data();
425 if (optional_roller_falcon.has_value()) {
426 roller_falcon_offset = frc971::control_loops::CANFalcon::Pack(
427 *builder.fbb(), &optional_roller_falcon.value());
428 }
429
430 superstructure::Position::Builder position_builder =
431 builder.MakeBuilder<superstructure::Position>();
432 position_builder.add_end_effector_cube_beam_break(
Maxwell Henderson3772d282023-11-06 11:07:49 -0800433 !end_effector_cube_beam_break_->Get());
Ariv Diggic892e922023-10-21 15:52:06 -0700434 if (!roller_falcon_offset.IsNull()) {
435 position_builder.add_roller_falcon(roller_falcon_offset);
436 }
437 builder.CheckOk(builder.Send(position_builder.Finish()));
438 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700439
440 {
441 auto builder = drivetrain_position_sender_.MakeBuilder();
442 frc971::control_loops::drivetrain::Position::Builder drivetrain_builder =
443 builder.MakeBuilder<frc971::control_loops::drivetrain::Position>();
444 drivetrain_builder.add_left_encoder(
445 constants::Values::DrivetrainEncoderToMeters(
446 drivetrain_left_encoder_->GetRaw()));
447 drivetrain_builder.add_left_speed(
448 drivetrain_velocity_translate(drivetrain_left_encoder_->GetPeriod()));
449
450 drivetrain_builder.add_right_encoder(
451 -constants::Values::DrivetrainEncoderToMeters(
452 drivetrain_right_encoder_->GetRaw()));
453 drivetrain_builder.add_right_speed(-drivetrain_velocity_translate(
454 drivetrain_right_encoder_->GetPeriod()));
455
456 builder.CheckOk(builder.Send(drivetrain_builder.Finish()));
457 }
458
459 {
460 auto builder = gyro_sender_.MakeBuilder();
461 ::frc971::sensors::GyroReading::Builder gyro_reading_builder =
462 builder.MakeBuilder<::frc971::sensors::GyroReading>();
463 // +/- 2000 deg / sec
464 constexpr double kMaxVelocity = 4000; // degrees / second
465 constexpr double kVelocityRadiansPerSecond =
466 kMaxVelocity / 360 * (2.0 * M_PI);
467
468 // Only part of the full range is used to prevent being 100% on or off.
469 constexpr double kScaledRangeLow = 0.1;
470 constexpr double kScaledRangeHigh = 0.9;
471
472 constexpr double kPWMFrequencyHz = 200;
473 double velocity_duty_cycle =
474 imu_yaw_rate_reader_.last_width() * kPWMFrequencyHz;
475
476 constexpr double kDutyCycleScale =
477 1 / (kScaledRangeHigh - kScaledRangeLow);
478 // scale from 0.1 - 0.9 to 0 - 1
479 double rescaled_velocity_duty_cycle =
480 (velocity_duty_cycle - kScaledRangeLow) * kDutyCycleScale;
481
482 if (!std::isnan(rescaled_velocity_duty_cycle)) {
483 gyro_reading_builder.add_velocity((rescaled_velocity_duty_cycle - 0.5) *
484 kVelocityRadiansPerSecond);
485 }
486 builder.CheckOk(builder.Send(gyro_reading_builder.Finish()));
487 }
488
489 {
490 auto builder = auto_mode_sender_.MakeBuilder();
491
492 uint32_t mode = 0;
493 for (size_t i = 0; i < autonomous_modes_.size(); ++i) {
494 if (autonomous_modes_[i] && autonomous_modes_[i]->Get()) {
495 mode |= 1 << i;
496 }
497 }
498
499 auto auto_mode_builder =
500 builder.MakeBuilder<frc971::autonomous::AutonomousMode>();
501
502 auto_mode_builder.add_mode(mode);
503
504 builder.CheckOk(builder.Send(auto_mode_builder.Finish()));
505 }
506 }
507
508 std::shared_ptr<frc::DigitalOutput> superstructure_reading_;
509
510 void set_superstructure_reading(
511 std::shared_ptr<frc::DigitalOutput> superstructure_reading) {
512 superstructure_reading_ = superstructure_reading;
513 }
514
Maxwell Henderson3772d282023-11-06 11:07:49 -0800515 void set_end_effector_cube_beam_break(
516 ::std::unique_ptr<frc::DigitalInput> sensor) {
517 end_effector_cube_beam_break_ = ::std::move(sensor);
518 }
519
Ariv Diggi0af59c02023-10-07 13:15:39 -0700520 private:
521 std::shared_ptr<const Values> values_;
522
523 aos::Sender<frc971::autonomous::AutonomousMode> auto_mode_sender_;
524 aos::Sender<superstructure::Position> superstructure_position_sender_;
525 aos::Sender<frc971::control_loops::drivetrain::Position>
526 drivetrain_position_sender_;
527 ::aos::Sender<::frc971::sensors::GyroReading> gyro_sender_;
528
529 std::array<std::unique_ptr<frc::DigitalInput>, 2> autonomous_modes_;
530
Ariv Diggic892e922023-10-21 15:52:06 -0700531 std::unique_ptr<frc::DigitalInput> imu_yaw_rate_input_,
532 end_effector_cube_beam_break_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700533
534 frc971::wpilib::DMAPulseWidthReader imu_yaw_rate_reader_;
535
536 CANSensorReader *can_sensor_reader_;
537};
538
539class SuperstructureWriter
540 : public ::frc971::wpilib::LoopOutputHandler<superstructure::Output> {
541 public:
542 SuperstructureWriter(aos::EventLoop *event_loop)
543 : frc971::wpilib::LoopOutputHandler<superstructure::Output>(
544 event_loop, "/superstructure") {
545 event_loop->SetRuntimeRealtimePriority(
546 constants::Values::kDrivetrainWriterPriority);
547 }
548
549 std::shared_ptr<frc::DigitalOutput> superstructure_reading_;
550
551 void set_superstructure_reading(
552 std::shared_ptr<frc::DigitalOutput> superstructure_reading) {
553 superstructure_reading_ = superstructure_reading;
554 }
555
556 private:
557 void Stop() override { AOS_LOG(WARNING, "Superstructure output too old.\n"); }
558
559 void Write(const superstructure::Output &output) override { (void)output; }
560
561 static void WriteCan(const double voltage,
562 ::ctre::phoenix::motorcontrol::can::TalonFX *falcon) {
563 falcon->Set(
564 ctre::phoenix::motorcontrol::ControlMode::PercentOutput,
565 std::clamp(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
566 }
567
568 template <typename T>
569 static void WritePwm(const double voltage, T *motor) {
570 motor->SetSpeed(std::clamp(voltage, -kMaxBringupPower, kMaxBringupPower) /
571 12.0);
572 }
573};
574
575class SuperstructureCANWriter
576 : public ::frc971::wpilib::LoopOutputHandler<superstructure::Output> {
577 public:
578 SuperstructureCANWriter(::aos::EventLoop *event_loop)
579 : ::frc971::wpilib::LoopOutputHandler<superstructure::Output>(
580 event_loop, "/superstructure") {
581 event_loop->SetRuntimeRealtimePriority(
582 constants::Values::kSuperstructureCANWriterPriority);
583
584 event_loop->OnRun([this]() { WriteConfigs(); });
585 };
586
587 void HandleCANConfiguration(const frc971::CANConfiguration &configuration) {
Maxwell Henderson3772d282023-11-06 11:07:49 -0800588 roller_falcon_->PrintConfigs();
Ariv Diggi0af59c02023-10-07 13:15:39 -0700589 if (configuration.reapply()) {
590 WriteConfigs();
591 }
592 }
593
Maxwell Henderson3772d282023-11-06 11:07:49 -0800594 void set_roller_falcon(std::shared_ptr<Falcon> roller_falcon) {
595 roller_falcon_ = std::move(roller_falcon);
596 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700597
Maxwell Henderson3772d282023-11-06 11:07:49 -0800598 private:
599 void WriteConfigs() { roller_falcon_->WriteRollerConfigs(); }
600
601 void Write(const superstructure::Output &output) override {
602 ctre::phoenix6::controls::DutyCycleOut roller_control(
603 SafeSpeed(-output.roller_voltage()));
604 roller_control.UpdateFreqHz = 0_Hz;
605 roller_control.EnableFOC = true;
606
607 ctre::phoenix::StatusCode status =
608 roller_falcon_->talon()->SetControl(roller_control);
609
610 if (!status.IsOK()) {
611 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
612 status.GetName(), status.GetDescription());
613 }
614 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700615
616 void Stop() override {
617 AOS_LOG(WARNING, "Superstructure CAN output too old.\n");
618 ctre::phoenix6::controls::DutyCycleOut stop_command(0.0);
619 stop_command.UpdateFreqHz = 0_Hz;
620 stop_command.EnableFOC = true;
Maxwell Henderson3772d282023-11-06 11:07:49 -0800621
622 roller_falcon_->talon()->SetControl(stop_command);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700623 }
624
625 double SafeSpeed(double voltage) {
626 return (::aos::Clip(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
627 }
Maxwell Henderson3772d282023-11-06 11:07:49 -0800628
629 std::shared_ptr<Falcon> roller_falcon_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700630};
631
632class DrivetrainWriter : public ::frc971::wpilib::LoopOutputHandler<
633 ::frc971::control_loops::drivetrain::Output> {
634 public:
635 DrivetrainWriter(::aos::EventLoop *event_loop)
636 : ::frc971::wpilib::LoopOutputHandler<
637 ::frc971::control_loops::drivetrain::Output>(event_loop,
638 "/drivetrain") {
639 event_loop->SetRuntimeRealtimePriority(
640 constants::Values::kDrivetrainWriterPriority);
641
642 event_loop->OnRun([this]() { WriteConfigs(); });
643 }
644
645 void set_falcons(std::shared_ptr<Falcon> right_front,
646 std::shared_ptr<Falcon> right_back,
Ariv Diggi0af59c02023-10-07 13:15:39 -0700647 std::shared_ptr<Falcon> left_front,
Mirabel Wangf4e42672023-10-14 13:12:49 -0700648 std::shared_ptr<Falcon> left_back) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700649 right_front_ = std::move(right_front);
650 right_back_ = std::move(right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700651 left_front_ = std::move(left_front);
652 left_back_ = std::move(left_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700653 }
654
655 void set_right_inverted(ctre::phoenix6::signals::InvertedValue invert) {
656 right_inverted_ = invert;
657 }
658
659 void set_left_inverted(ctre::phoenix6::signals::InvertedValue invert) {
660 left_inverted_ = invert;
661 }
662
663 void HandleCANConfiguration(const frc971::CANConfiguration &configuration) {
Mirabel Wangf4e42672023-10-14 13:12:49 -0700664 for (auto falcon : {right_front_, right_back_, left_front_, left_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700665 falcon->PrintConfigs();
666 }
667 if (configuration.reapply()) {
668 WriteConfigs();
669 }
670 }
671
672 private:
673 void WriteConfigs() {
Mirabel Wangf4e42672023-10-14 13:12:49 -0700674 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700675 falcon->WriteConfigs(right_inverted_);
676 }
677
Mirabel Wangf4e42672023-10-14 13:12:49 -0700678 for (auto falcon : {left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700679 falcon->WriteConfigs(left_inverted_);
680 }
681 }
682
683 void Write(
684 const ::frc971::control_loops::drivetrain::Output &output) override {
685 ctre::phoenix6::controls::DutyCycleOut left_control(
686 SafeSpeed(output.left_voltage()));
687 left_control.UpdateFreqHz = 0_Hz;
688 left_control.EnableFOC = true;
689
690 ctre::phoenix6::controls::DutyCycleOut right_control(
691 SafeSpeed(output.right_voltage()));
692 right_control.UpdateFreqHz = 0_Hz;
693 right_control.EnableFOC = true;
694
Mirabel Wangf4e42672023-10-14 13:12:49 -0700695 for (auto falcon : {left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700696 ctre::phoenix::StatusCode status =
697 falcon->talon()->SetControl(left_control);
698
699 if (!status.IsOK()) {
700 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
701 status.GetName(), status.GetDescription());
702 }
703 }
704
Mirabel Wangf4e42672023-10-14 13:12:49 -0700705 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700706 ctre::phoenix::StatusCode status =
707 falcon->talon()->SetControl(right_control);
708
709 if (!status.IsOK()) {
710 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
711 status.GetName(), status.GetDescription());
712 }
713 }
714 }
715
716 void Stop() override {
717 AOS_LOG(WARNING, "drivetrain output too old\n");
718 ctre::phoenix6::controls::DutyCycleOut stop_command(0.0);
719 stop_command.UpdateFreqHz = 0_Hz;
720 stop_command.EnableFOC = true;
721
Mirabel Wangf4e42672023-10-14 13:12:49 -0700722 for (auto falcon : {right_front_.get(), right_back_.get(),
723 left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700724 falcon->talon()->SetControl(stop_command);
725 }
726 }
727
728 double SafeSpeed(double voltage) {
729 return (::aos::Clip(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
730 }
731
732 ctre::phoenix6::signals::InvertedValue left_inverted_, right_inverted_;
Mirabel Wangf4e42672023-10-14 13:12:49 -0700733 std::shared_ptr<Falcon> right_front_, right_back_, left_front_, left_back_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700734};
735
736class WPILibRobot : public ::frc971::wpilib::WPILibRobotBase {
737 public:
738 ::std::unique_ptr<frc::Encoder> make_encoder(int index) {
739 return make_unique<frc::Encoder>(10 + index * 2, 11 + index * 2, false,
740 frc::Encoder::k4X);
741 }
742
743 void Run() override {
744 std::shared_ptr<const Values> values =
745 std::make_shared<const Values>(constants::MakeValues());
746
747 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
748 aos::configuration::ReadConfig("aos_config.json");
749
750 // Thread 1.
751 ::aos::ShmEventLoop joystick_sender_event_loop(&config.message());
752 ::frc971::wpilib::JoystickSender joystick_sender(
753 &joystick_sender_event_loop);
754 AddLoop(&joystick_sender_event_loop);
755
756 // Thread 2.
757 ::aos::ShmEventLoop pdp_fetcher_event_loop(&config.message());
758 ::frc971::wpilib::PDPFetcher pdp_fetcher(&pdp_fetcher_event_loop);
759 AddLoop(&pdp_fetcher_event_loop);
760
761 std::shared_ptr<frc::DigitalOutput> superstructure_reading =
762 make_unique<frc::DigitalOutput>(25);
763
764 std::vector<ctre::phoenix6::BaseStatusSignal *> signals_registry;
765 std::shared_ptr<Falcon> right_front =
766 std::make_shared<Falcon>(1, "Drivetrain Bus", &signals_registry);
767 std::shared_ptr<Falcon> right_back =
Maxwell Henderson3772d282023-11-06 11:07:49 -0800768 std::make_shared<Falcon>(0, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700769 std::shared_ptr<Falcon> left_front =
Maxwell Henderson3772d282023-11-06 11:07:49 -0800770 std::make_shared<Falcon>(2, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700771 std::shared_ptr<Falcon> left_back =
Maxwell Henderson3772d282023-11-06 11:07:49 -0800772 std::make_shared<Falcon>(3, "Drivetrain Bus", &signals_registry);
773 std::shared_ptr<Falcon> roller =
Ariv Diggi0af59c02023-10-07 13:15:39 -0700774 std::make_shared<Falcon>(5, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700775
776 // Thread 3.
777 ::aos::ShmEventLoop can_sensor_reader_event_loop(&config.message());
778 can_sensor_reader_event_loop.set_name("CANSensorReader");
779 CANSensorReader can_sensor_reader(&can_sensor_reader_event_loop,
780 std::move(signals_registry));
781
Mirabel Wangf4e42672023-10-14 13:12:49 -0700782 can_sensor_reader.set_falcons(right_front, right_back, left_front,
Maxwell Henderson3772d282023-11-06 11:07:49 -0800783 left_back, roller);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700784
785 AddLoop(&can_sensor_reader_event_loop);
786
787 // Thread 4.
788 ::aos::ShmEventLoop sensor_reader_event_loop(&config.message());
789 SensorReader sensor_reader(&sensor_reader_event_loop, values,
790 &can_sensor_reader);
791 sensor_reader.set_pwm_trigger(true);
792 sensor_reader.set_drivetrain_left_encoder(make_encoder(1));
793 sensor_reader.set_drivetrain_right_encoder(make_encoder(0));
794 sensor_reader.set_superstructure_reading(superstructure_reading);
795 sensor_reader.set_yaw_rate_input(make_unique<frc::DigitalInput>(0));
Maxwell Henderson3772d282023-11-06 11:07:49 -0800796 sensor_reader.set_end_effector_cube_beam_break(
797 make_unique<frc::DigitalInput>(22));
Ariv Diggi0af59c02023-10-07 13:15:39 -0700798
799 AddLoop(&sensor_reader_event_loop);
800
801 // Thread 5.
802 // Set up CAN.
803 if (!FLAGS_ctre_diag_server) {
804 c_Phoenix_Diagnostics_SetSecondsToStart(-1);
805 c_Phoenix_Diagnostics_Dispose();
806 }
807
808 ctre::phoenix::platform::can::CANComm_SetRxSchedPriority(
809 constants::Values::kDrivetrainRxPriority, true, "Drivetrain Bus");
810 ctre::phoenix::platform::can::CANComm_SetTxSchedPriority(
811 constants::Values::kDrivetrainTxPriority, true, "Drivetrain Bus");
812
813 ::aos::ShmEventLoop can_output_event_loop(&config.message());
814 can_output_event_loop.set_name("CANOutputWriter");
815 DrivetrainWriter drivetrain_writer(&can_output_event_loop);
816
Mirabel Wangf4e42672023-10-14 13:12:49 -0700817 drivetrain_writer.set_falcons(right_front, right_back, left_front,
818 left_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700819 drivetrain_writer.set_right_inverted(
820 ctre::phoenix6::signals::InvertedValue::Clockwise_Positive);
821 drivetrain_writer.set_left_inverted(
822 ctre::phoenix6::signals::InvertedValue::CounterClockwise_Positive);
823
824 can_output_event_loop.MakeWatcher(
825 "/roborio",
826 [&drivetrain_writer](const frc971::CANConfiguration &configuration) {
827 drivetrain_writer.HandleCANConfiguration(configuration);
828 });
829
830 AddLoop(&can_output_event_loop);
831
832 // Thread 6
833 // Set up superstructure output.
834 ::aos::ShmEventLoop output_event_loop(&config.message());
835 output_event_loop.set_name("PWMOutputWriter");
836 SuperstructureWriter superstructure_writer(&output_event_loop);
837
838 superstructure_writer.set_superstructure_reading(superstructure_reading);
839
840 AddLoop(&output_event_loop);
841
842 // Thread 7
Maxwell Henderson3772d282023-11-06 11:07:49 -0800843 // Setup superstructure CAN output.
844 SuperstructureCANWriter superstructure_can_writer(&can_output_event_loop);
845 superstructure_can_writer.set_roller_falcon(roller);
846
847 can_output_event_loop.MakeWatcher(
848 "/roborio", [&drivetrain_writer, &superstructure_can_writer](
849 const frc971::CANConfiguration &configuration) {
850 drivetrain_writer.HandleCANConfiguration(configuration);
851 superstructure_can_writer.HandleCANConfiguration(configuration);
852 });
853
854 AddLoop(&can_output_event_loop);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700855
856 RunLoops();
857 }
858};
859
860} // namespace wpilib
861} // namespace y2023_bot3
862
863AOS_ROBOT_CLASS(::y2023_bot3::wpilib::WPILibRobot);