blob: e91f6e784928e93181a0e5e7ca48412a1236045d [file] [log] [blame]
Ariv Diggi0af59c02023-10-07 13:15:39 -07001#include <unistd.h>
2
3#include <array>
4#include <chrono>
5#include <cinttypes>
6#include <cmath>
7#include <cstdio>
8#include <cstring>
9#include <functional>
10#include <memory>
11#include <mutex>
12#include <thread>
13
14#include "ctre/phoenix/CANifier.h"
15
16#include "frc971/wpilib/ahal/AnalogInput.h"
17#include "frc971/wpilib/ahal/Counter.h"
18#include "frc971/wpilib/ahal/DigitalGlitchFilter.h"
19#include "frc971/wpilib/ahal/DriverStation.h"
20#include "frc971/wpilib/ahal/Encoder.h"
21#include "frc971/wpilib/ahal/Servo.h"
22#include "frc971/wpilib/ahal/TalonFX.h"
23#include "frc971/wpilib/ahal/VictorSP.h"
24#undef ERROR
25
26#include "ctre/phoenix/cci/Diagnostics_CCI.h"
Ariv Diggi0af59c02023-10-07 13:15:39 -070027#include "ctre/phoenix6/TalonFX.hpp"
28
29#include "aos/commonmath.h"
30#include "aos/containers/sized_array.h"
31#include "aos/events/event_loop.h"
32#include "aos/events/shm_event_loop.h"
33#include "aos/init.h"
34#include "aos/logging/logging.h"
35#include "aos/realtime.h"
36#include "aos/time/time.h"
37#include "aos/util/log_interval.h"
38#include "aos/util/phased_loop.h"
39#include "aos/util/wrapping_counter.h"
40#include "frc971/autonomous/auto_mode_generated.h"
41#include "frc971/can_configuration_generated.h"
42#include "frc971/control_loops/drivetrain/drivetrain_can_position_generated.h"
43#include "frc971/control_loops/drivetrain/drivetrain_position_generated.h"
44#include "frc971/input/robot_state_generated.h"
45#include "frc971/queues/gyro_generated.h"
46#include "frc971/wpilib/ADIS16448.h"
47#include "frc971/wpilib/buffered_pcm.h"
48#include "frc971/wpilib/buffered_solenoid.h"
49#include "frc971/wpilib/dma.h"
50#include "frc971/wpilib/drivetrain_writer.h"
51#include "frc971/wpilib/encoder_and_potentiometer.h"
52#include "frc971/wpilib/joystick_sender.h"
53#include "frc971/wpilib/logging_generated.h"
54#include "frc971/wpilib/loop_output_handler.h"
55#include "frc971/wpilib/pdp_fetcher.h"
56#include "frc971/wpilib/sensor_reader.h"
57#include "frc971/wpilib/wpilib_robot_base.h"
58#include "y2023_bot3/constants.h"
59#include "y2023_bot3/control_loops/superstructure/led_indicator.h"
60#include "y2023_bot3/control_loops/superstructure/superstructure_output_generated.h"
61#include "y2023_bot3/control_loops/superstructure/superstructure_position_generated.h"
62
63DEFINE_bool(ctre_diag_server, false,
64 "If true, enable the diagnostics server for interacting with "
65 "devices on the CAN bus using Phoenix Tuner");
66
67using ::aos::monotonic_clock;
68using ::y2023_bot3::constants::Values;
69namespace superstructure = ::y2023_bot3::control_loops::superstructure;
70namespace drivetrain = ::y2023_bot3::control_loops::drivetrain;
71namespace chrono = ::std::chrono;
72using std::make_unique;
73
74namespace y2023_bot3 {
75namespace wpilib {
76namespace {
77
78constexpr double kMaxBringupPower = 12.0;
79
80// TODO(Brian): Fix the interpretation of the result of GetRaw here and in the
81// DMA stuff and then removing the * 2.0 in *_translate.
82// The low bit is direction.
83
84double drivetrain_velocity_translate(double in) {
85 return (((1.0 / in) / Values::kDrivetrainCyclesPerRevolution()) *
86 (2.0 * M_PI)) *
87 Values::kDrivetrainEncoderRatio() *
88 control_loops::drivetrain::kWheelRadius;
89}
90
Maxwell Henderson9435b5c2023-11-06 13:48:51 -080091double pivot_pot_translate(double voltage) {
92 return voltage * Values::kPivotJointPotRadiansPerVolt();
93}
94
Ariv Diggi0af59c02023-10-07 13:15:39 -070095constexpr double kMaxFastEncoderPulsesPerSecond = std::max({
96 Values::kMaxDrivetrainEncoderPulsesPerSecond(),
Maxwell Henderson0d220772023-11-06 11:09:58 -080097 Values::kMaxPivotJointEncoderPulsesPerSecond(),
Ariv Diggi0af59c02023-10-07 13:15:39 -070098});
99static_assert(kMaxFastEncoderPulsesPerSecond <= 1300000,
100 "fast encoders are too fast");
101
102} // namespace
103
104static constexpr int kCANFalconCount = 6;
105static constexpr units::frequency::hertz_t kCANUpdateFreqHz = 200_Hz;
106
107class Falcon {
108 public:
109 Falcon(int device_id, std::string canbus,
110 std::vector<ctre::phoenix6::BaseStatusSignal *> *signals)
111 : talon_(device_id, canbus),
112 device_id_(device_id),
113 device_temp_(talon_.GetDeviceTemp()),
114 supply_voltage_(talon_.GetSupplyVoltage()),
115 supply_current_(talon_.GetSupplyCurrent()),
116 torque_current_(talon_.GetTorqueCurrent()),
117 position_(talon_.GetPosition()),
118 duty_cycle_(talon_.GetDutyCycle()) {
119 // device temp is not timesynced so don't add it to the list of signals
120 device_temp_.SetUpdateFrequency(kCANUpdateFreqHz);
121
122 CHECK_NOTNULL(signals);
123
124 supply_voltage_.SetUpdateFrequency(kCANUpdateFreqHz);
125 signals->push_back(&supply_voltage_);
126
127 supply_current_.SetUpdateFrequency(kCANUpdateFreqHz);
128 signals->push_back(&supply_current_);
129
130 torque_current_.SetUpdateFrequency(kCANUpdateFreqHz);
131 signals->push_back(&torque_current_);
132
133 position_.SetUpdateFrequency(kCANUpdateFreqHz);
134 signals->push_back(&position_);
135
136 duty_cycle_.SetUpdateFrequency(kCANUpdateFreqHz);
137 signals->push_back(&duty_cycle_);
138 }
139
140 void PrintConfigs() {
141 ctre::phoenix6::configs::TalonFXConfiguration configuration;
142 ctre::phoenix::StatusCode status =
143 talon_.GetConfigurator().Refresh(configuration);
144 if (!status.IsOK()) {
145 AOS_LOG(ERROR, "Failed to get falcon configuration: %s: %s",
146 status.GetName(), status.GetDescription());
147 }
148 AOS_LOG(INFO, "configuration: %s", configuration.ToString().c_str());
149 }
150
151 void WriteConfigs(ctre::phoenix6::signals::InvertedValue invert) {
152 inverted_ = invert;
153
154 ctre::phoenix6::configs::CurrentLimitsConfigs current_limits;
155 current_limits.StatorCurrentLimit =
156 constants::Values::kDrivetrainStatorCurrentLimit();
157 current_limits.StatorCurrentLimitEnable = true;
158 current_limits.SupplyCurrentLimit =
159 constants::Values::kDrivetrainSupplyCurrentLimit();
160 current_limits.SupplyCurrentLimitEnable = true;
161
162 ctre::phoenix6::configs::MotorOutputConfigs output_configs;
163 output_configs.NeutralMode =
164 ctre::phoenix6::signals::NeutralModeValue::Brake;
165 output_configs.DutyCycleNeutralDeadband = 0;
166
167 output_configs.Inverted = inverted_;
168
169 ctre::phoenix6::configs::TalonFXConfiguration configuration;
170 configuration.CurrentLimits = current_limits;
171 configuration.MotorOutput = output_configs;
172
173 ctre::phoenix::StatusCode status =
174 talon_.GetConfigurator().Apply(configuration);
175 if (!status.IsOK()) {
176 AOS_LOG(ERROR, "Failed to set falcon configuration: %s: %s",
177 status.GetName(), status.GetDescription());
178 }
179
180 PrintConfigs();
181 }
182
Maxwell Henderson3772d282023-11-06 11:07:49 -0800183 void WriteRollerConfigs() {
184 ctre::phoenix6::configs::CurrentLimitsConfigs current_limits;
185 current_limits.StatorCurrentLimit =
186 constants::Values::kRollerStatorCurrentLimit();
187 current_limits.StatorCurrentLimitEnable = true;
188 current_limits.SupplyCurrentLimit =
189 constants::Values::kRollerSupplyCurrentLimit();
190 current_limits.SupplyCurrentLimitEnable = true;
191
192 ctre::phoenix6::configs::MotorOutputConfigs output_configs;
193 output_configs.NeutralMode =
194 ctre::phoenix6::signals::NeutralModeValue::Brake;
195 output_configs.DutyCycleNeutralDeadband = 0;
196
197 ctre::phoenix6::configs::TalonFXConfiguration configuration;
198 configuration.CurrentLimits = current_limits;
199 configuration.MotorOutput = output_configs;
200
201 ctre::phoenix::StatusCode status =
202 talon_.GetConfigurator().Apply(configuration);
203 if (!status.IsOK()) {
204 AOS_LOG(ERROR, "Failed to set falcon configuration: %s: %s",
205 status.GetName(), status.GetDescription());
206 }
207
208 PrintConfigs();
209 }
210
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800211 void WritePivotConfigs() {
212 ctre::phoenix6::configs::CurrentLimitsConfigs current_limits;
213 current_limits.StatorCurrentLimit =
214 constants::Values::kPivotStatorCurrentLimit();
215 current_limits.StatorCurrentLimitEnable = true;
216 current_limits.SupplyCurrentLimit =
217 constants::Values::kPivotSupplyCurrentLimit();
218 current_limits.SupplyCurrentLimitEnable = true;
219
220 ctre::phoenix6::configs::MotorOutputConfigs output_configs;
221 output_configs.NeutralMode =
222 ctre::phoenix6::signals::NeutralModeValue::Brake;
223 output_configs.DutyCycleNeutralDeadband = 0;
224
225 ctre::phoenix6::configs::TalonFXConfiguration configuration;
226 configuration.CurrentLimits = current_limits;
227 configuration.MotorOutput = output_configs;
228
229 ctre::phoenix::StatusCode status =
230 talon_.GetConfigurator().Apply(configuration);
231 if (!status.IsOK()) {
232 AOS_LOG(ERROR, "Failed to set falcon configuration: %s: %s",
233 status.GetName(), status.GetDescription());
234 }
235
236 PrintConfigs();
237 }
238
Ariv Diggi0af59c02023-10-07 13:15:39 -0700239 ctre::phoenix6::hardware::TalonFX *talon() { return &talon_; }
240
241 flatbuffers::Offset<frc971::control_loops::CANFalcon> WritePosition(
242 flatbuffers::FlatBufferBuilder *fbb) {
243 frc971::control_loops::CANFalcon::Builder builder(*fbb);
244 builder.add_id(device_id_);
245 builder.add_device_temp(device_temp());
246 builder.add_supply_voltage(supply_voltage());
247 builder.add_supply_current(supply_current());
248 builder.add_torque_current(torque_current());
249 builder.add_duty_cycle(duty_cycle());
250
251 double invert =
252 (inverted_ == ctre::phoenix6::signals::InvertedValue::Clockwise_Positive
253 ? 1
254 : -1);
255
256 builder.add_position(
257 constants::Values::DrivetrainCANEncoderToMeters(position()) * invert);
258
259 return builder.Finish();
260 }
261
262 int device_id() const { return device_id_; }
263 float device_temp() const { return device_temp_.GetValue().value(); }
264 float supply_voltage() const { return supply_voltage_.GetValue().value(); }
265 float supply_current() const { return supply_current_.GetValue().value(); }
266 float torque_current() const { return torque_current_.GetValue().value(); }
267 float duty_cycle() const { return duty_cycle_.GetValue().value(); }
268 float position() const { return position_.GetValue().value(); }
269
270 // returns the monotonic timestamp of the latest timesynced reading in the
271 // timebase of the the syncronized CAN bus clock.
272 int64_t GetTimestamp() {
273 std::chrono::nanoseconds latest_timestamp =
274 torque_current_.GetTimestamp().GetTime();
275
276 return latest_timestamp.count();
277 }
278
279 void RefreshNontimesyncedSignals() { device_temp_.Refresh(); };
280
281 private:
282 ctre::phoenix6::hardware::TalonFX talon_;
283 int device_id_;
284
285 ctre::phoenix6::signals::InvertedValue inverted_;
286
287 ctre::phoenix6::StatusSignal<units::temperature::celsius_t> device_temp_;
288 ctre::phoenix6::StatusSignal<units::voltage::volt_t> supply_voltage_;
289 ctre::phoenix6::StatusSignal<units::current::ampere_t> supply_current_,
290 torque_current_;
291 ctre::phoenix6::StatusSignal<units::angle::turn_t> position_;
292 ctre::phoenix6::StatusSignal<units::dimensionless::scalar_t> duty_cycle_;
293};
294
295class CANSensorReader {
296 public:
297 CANSensorReader(
298 aos::EventLoop *event_loop,
299 std::vector<ctre::phoenix6::BaseStatusSignal *> signals_registry)
300 : event_loop_(event_loop),
301 signals_(signals_registry.begin(), signals_registry.end()),
302 can_position_sender_(
303 event_loop
304 ->MakeSender<frc971::control_loops::drivetrain::CANPosition>(
Maxwell Henderson3772d282023-11-06 11:07:49 -0800305 "/drivetrain")),
306 roller_falcon_data_(std::nullopt) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700307 event_loop->SetRuntimeRealtimePriority(40);
308 event_loop->SetRuntimeAffinity(aos::MakeCpusetFromCpus({1}));
309 timer_handler_ = event_loop->AddTimer([this]() { Loop(); });
310 timer_handler_->set_name("CANSensorReader Loop");
311
312 event_loop->OnRun([this]() {
313 timer_handler_->Schedule(event_loop_->monotonic_now(),
314 1 / kCANUpdateFreqHz);
315 });
316 }
317
318 void set_falcons(std::shared_ptr<Falcon> right_front,
319 std::shared_ptr<Falcon> right_back,
Ariv Diggi0af59c02023-10-07 13:15:39 -0700320 std::shared_ptr<Falcon> left_front,
Ariv Diggic892e922023-10-21 15:52:06 -0700321 std::shared_ptr<Falcon> left_back,
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800322 std::shared_ptr<Falcon> roller_falcon,
323 std::shared_ptr<Falcon> pivot_falcon) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700324 right_front_ = std::move(right_front);
325 right_back_ = std::move(right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700326 left_front_ = std::move(left_front);
327 left_back_ = std::move(left_back);
Maxwell Henderson3772d282023-11-06 11:07:49 -0800328 roller_falcon_ = std::move(roller_falcon);
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800329 pivot_falcon_ = std::move(pivot_falcon);
Ariv Diggic892e922023-10-21 15:52:06 -0700330 }
331
332 std::optional<frc971::control_loops::CANFalconT> roller_falcon_data() {
333 std::unique_lock<aos::stl_mutex> lock(roller_mutex_);
334 return roller_falcon_data_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700335 }
336
337 private:
338 void Loop() {
339 ctre::phoenix::StatusCode status =
340 ctre::phoenix6::BaseStatusSignal::WaitForAll(2000_ms, signals_);
341
342 if (!status.IsOK()) {
343 AOS_LOG(ERROR, "Failed to read signals from falcons: %s: %s",
344 status.GetName(), status.GetDescription());
345 }
346
347 auto builder = can_position_sender_.MakeBuilder();
348
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800349 for (auto falcon : {right_front_, right_back_, left_front_, left_back_,
350 roller_falcon_, pivot_falcon_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700351 falcon->RefreshNontimesyncedSignals();
352 }
353
354 aos::SizedArray<flatbuffers::Offset<frc971::control_loops::CANFalcon>,
355 kCANFalconCount>
356 falcons;
357
Mirabel Wangf4e42672023-10-14 13:12:49 -0700358 for (auto falcon : {right_front_, right_back_, left_front_, left_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700359 falcons.push_back(falcon->WritePosition(builder.fbb()));
360 }
361
362 auto falcons_list =
363 builder.fbb()
364 ->CreateVector<
365 flatbuffers::Offset<frc971::control_loops::CANFalcon>>(falcons);
366
367 frc971::control_loops::drivetrain::CANPosition::Builder
368 can_position_builder =
369 builder
370 .MakeBuilder<frc971::control_loops::drivetrain::CANPosition>();
371
372 can_position_builder.add_falcons(falcons_list);
373 can_position_builder.add_timestamp(right_front_->GetTimestamp());
374 can_position_builder.add_status(static_cast<int>(status));
375
376 builder.CheckOk(builder.Send(can_position_builder.Finish()));
Maxwell Henderson3772d282023-11-06 11:07:49 -0800377
378 {
379 std::unique_lock<aos::stl_mutex> lock(roller_mutex_);
380 frc971::control_loops::CANFalconT roller_falcon_data;
381 roller_falcon_data.id = roller_falcon_->device_id();
382 roller_falcon_data.supply_current = roller_falcon_->supply_current();
383 roller_falcon_data.torque_current = -roller_falcon_->torque_current();
384 roller_falcon_data.supply_voltage = roller_falcon_->supply_voltage();
385 roller_falcon_data.device_temp = roller_falcon_->device_temp();
386 roller_falcon_data.position = -roller_falcon_->position();
387 roller_falcon_data.duty_cycle = roller_falcon_->duty_cycle();
388 roller_falcon_data_ =
389 std::make_optional<frc971::control_loops::CANFalconT>(
390 roller_falcon_data);
391 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700392 }
393
394 aos::EventLoop *event_loop_;
395
396 const std::vector<ctre::phoenix6::BaseStatusSignal *> signals_;
397 aos::Sender<frc971::control_loops::drivetrain::CANPosition>
398 can_position_sender_;
399
Ariv Diggic892e922023-10-21 15:52:06 -0700400 std::shared_ptr<Falcon> right_front_, right_back_, left_front_, left_back_,
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800401 roller_falcon_, pivot_falcon_;
Ariv Diggic892e922023-10-21 15:52:06 -0700402
403 std::optional<frc971::control_loops::CANFalconT> roller_falcon_data_;
404
405 aos::stl_mutex roller_mutex_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700406
407 // Pointer to the timer handler used to modify the wakeup.
408 ::aos::TimerHandler *timer_handler_;
409};
410
411// Class to send position messages with sensor readings to our loops.
412class SensorReader : public ::frc971::wpilib::SensorReader {
413 public:
414 SensorReader(::aos::ShmEventLoop *event_loop,
415 std::shared_ptr<const Values> values,
416 CANSensorReader *can_sensor_reader)
417 : ::frc971::wpilib::SensorReader(event_loop),
418 values_(std::move(values)),
419 auto_mode_sender_(
420 event_loop->MakeSender<::frc971::autonomous::AutonomousMode>(
421 "/autonomous")),
422 superstructure_position_sender_(
423 event_loop->MakeSender<superstructure::Position>(
424 "/superstructure")),
425 drivetrain_position_sender_(
426 event_loop
427 ->MakeSender<::frc971::control_loops::drivetrain::Position>(
428 "/drivetrain")),
429 gyro_sender_(event_loop->MakeSender<::frc971::sensors::GyroReading>(
430 "/drivetrain")),
431 can_sensor_reader_(can_sensor_reader) {
432 // Set to filter out anything shorter than 1/4 of the minimum pulse width
433 // we should ever see.
434 UpdateFastEncoderFilterHz(kMaxFastEncoderPulsesPerSecond);
435 event_loop->SetRuntimeAffinity(aos::MakeCpusetFromCpus({0}));
436 }
437
438 void Start() override { AddToDMA(&imu_yaw_rate_reader_); }
439
440 // Auto mode switches.
441 void set_autonomous_mode(int i, ::std::unique_ptr<frc::DigitalInput> sensor) {
442 autonomous_modes_.at(i) = ::std::move(sensor);
443 }
444
445 void set_yaw_rate_input(::std::unique_ptr<frc::DigitalInput> sensor) {
446 imu_yaw_rate_input_ = ::std::move(sensor);
447 imu_yaw_rate_reader_.set_input(imu_yaw_rate_input_.get());
448 }
449
450 void RunIteration() override {
451 superstructure_reading_->Set(true);
Ariv Diggic892e922023-10-21 15:52:06 -0700452 {
453 auto builder = superstructure_position_sender_.MakeBuilder();
454
455 flatbuffers::Offset<frc971::control_loops::CANFalcon>
456 roller_falcon_offset;
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800457 frc971::PotAndAbsolutePositionT pivot;
458 CopyPosition(pivot_encoder_, &pivot,
459 Values::kPivotJointEncoderCountsPerRevolution(),
460 Values::kPivotJointEncoderRatio(), pivot_pot_translate, true,
461 values_->pivot_joint.potentiometer_offset);
462
Ariv Diggic892e922023-10-21 15:52:06 -0700463 auto optional_roller_falcon = can_sensor_reader_->roller_falcon_data();
464 if (optional_roller_falcon.has_value()) {
465 roller_falcon_offset = frc971::control_loops::CANFalcon::Pack(
466 *builder.fbb(), &optional_roller_falcon.value());
467 }
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800468
469 flatbuffers::Offset<frc971::PotAndAbsolutePosition> pivot_offset =
470 frc971::PotAndAbsolutePosition::Pack(*builder.fbb(), &pivot);
471
Ariv Diggic892e922023-10-21 15:52:06 -0700472 superstructure::Position::Builder position_builder =
473 builder.MakeBuilder<superstructure::Position>();
474 position_builder.add_end_effector_cube_beam_break(
Maxwell Henderson3772d282023-11-06 11:07:49 -0800475 !end_effector_cube_beam_break_->Get());
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800476 position_builder.add_pivot_joint_position(pivot_offset);
Maxwell Henderson0d220772023-11-06 11:09:58 -0800477
Ariv Diggic892e922023-10-21 15:52:06 -0700478 if (!roller_falcon_offset.IsNull()) {
479 position_builder.add_roller_falcon(roller_falcon_offset);
480 }
481 builder.CheckOk(builder.Send(position_builder.Finish()));
482 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700483
484 {
485 auto builder = drivetrain_position_sender_.MakeBuilder();
486 frc971::control_loops::drivetrain::Position::Builder drivetrain_builder =
487 builder.MakeBuilder<frc971::control_loops::drivetrain::Position>();
488 drivetrain_builder.add_left_encoder(
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800489 -constants::Values::DrivetrainEncoderToMeters(
Ariv Diggi0af59c02023-10-07 13:15:39 -0700490 drivetrain_left_encoder_->GetRaw()));
491 drivetrain_builder.add_left_speed(
492 drivetrain_velocity_translate(drivetrain_left_encoder_->GetPeriod()));
493
494 drivetrain_builder.add_right_encoder(
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800495 constants::Values::DrivetrainEncoderToMeters(
Ariv Diggi0af59c02023-10-07 13:15:39 -0700496 drivetrain_right_encoder_->GetRaw()));
497 drivetrain_builder.add_right_speed(-drivetrain_velocity_translate(
498 drivetrain_right_encoder_->GetPeriod()));
499
500 builder.CheckOk(builder.Send(drivetrain_builder.Finish()));
501 }
502
503 {
504 auto builder = gyro_sender_.MakeBuilder();
505 ::frc971::sensors::GyroReading::Builder gyro_reading_builder =
506 builder.MakeBuilder<::frc971::sensors::GyroReading>();
507 // +/- 2000 deg / sec
508 constexpr double kMaxVelocity = 4000; // degrees / second
509 constexpr double kVelocityRadiansPerSecond =
510 kMaxVelocity / 360 * (2.0 * M_PI);
511
512 // Only part of the full range is used to prevent being 100% on or off.
513 constexpr double kScaledRangeLow = 0.1;
514 constexpr double kScaledRangeHigh = 0.9;
515
516 constexpr double kPWMFrequencyHz = 200;
517 double velocity_duty_cycle =
518 imu_yaw_rate_reader_.last_width() * kPWMFrequencyHz;
519
520 constexpr double kDutyCycleScale =
521 1 / (kScaledRangeHigh - kScaledRangeLow);
522 // scale from 0.1 - 0.9 to 0 - 1
523 double rescaled_velocity_duty_cycle =
524 (velocity_duty_cycle - kScaledRangeLow) * kDutyCycleScale;
525
526 if (!std::isnan(rescaled_velocity_duty_cycle)) {
527 gyro_reading_builder.add_velocity((rescaled_velocity_duty_cycle - 0.5) *
528 kVelocityRadiansPerSecond);
529 }
530 builder.CheckOk(builder.Send(gyro_reading_builder.Finish()));
531 }
532
533 {
534 auto builder = auto_mode_sender_.MakeBuilder();
535
536 uint32_t mode = 0;
537 for (size_t i = 0; i < autonomous_modes_.size(); ++i) {
538 if (autonomous_modes_[i] && autonomous_modes_[i]->Get()) {
539 mode |= 1 << i;
540 }
541 }
542
543 auto auto_mode_builder =
544 builder.MakeBuilder<frc971::autonomous::AutonomousMode>();
545
546 auto_mode_builder.add_mode(mode);
547
548 builder.CheckOk(builder.Send(auto_mode_builder.Finish()));
549 }
550 }
551
552 std::shared_ptr<frc::DigitalOutput> superstructure_reading_;
553
554 void set_superstructure_reading(
555 std::shared_ptr<frc::DigitalOutput> superstructure_reading) {
556 superstructure_reading_ = superstructure_reading;
557 }
558
Maxwell Henderson3772d282023-11-06 11:07:49 -0800559 void set_end_effector_cube_beam_break(
560 ::std::unique_ptr<frc::DigitalInput> sensor) {
561 end_effector_cube_beam_break_ = ::std::move(sensor);
562 }
563
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800564 void set_pivot_encoder(::std::unique_ptr<frc::Encoder> encoder) {
565 fast_encoder_filter_.Add(encoder.get());
566 pivot_encoder_.set_encoder(::std::move(encoder));
567 }
568
569 void set_pivot_absolute_pwm(
570 ::std::unique_ptr<frc::DigitalInput> absolute_pwm) {
571 pivot_encoder_.set_absolute_pwm(::std::move(absolute_pwm));
572 }
573
574 void set_pivot_potentiometer(
575 ::std::unique_ptr<frc::AnalogInput> potentiometer) {
576 pivot_encoder_.set_potentiometer(::std::move(potentiometer));
577 }
578
Ariv Diggi0af59c02023-10-07 13:15:39 -0700579 private:
580 std::shared_ptr<const Values> values_;
581
582 aos::Sender<frc971::autonomous::AutonomousMode> auto_mode_sender_;
583 aos::Sender<superstructure::Position> superstructure_position_sender_;
584 aos::Sender<frc971::control_loops::drivetrain::Position>
585 drivetrain_position_sender_;
586 ::aos::Sender<::frc971::sensors::GyroReading> gyro_sender_;
587
588 std::array<std::unique_ptr<frc::DigitalInput>, 2> autonomous_modes_;
589
Ariv Diggic892e922023-10-21 15:52:06 -0700590 std::unique_ptr<frc::DigitalInput> imu_yaw_rate_input_,
591 end_effector_cube_beam_break_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700592
593 frc971::wpilib::DMAPulseWidthReader imu_yaw_rate_reader_;
594
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800595 frc971::wpilib::AbsoluteEncoderAndPotentiometer pivot_encoder_;
596
Ariv Diggi0af59c02023-10-07 13:15:39 -0700597 CANSensorReader *can_sensor_reader_;
598};
599
Ariv Diggi0af59c02023-10-07 13:15:39 -0700600class SuperstructureCANWriter
601 : public ::frc971::wpilib::LoopOutputHandler<superstructure::Output> {
602 public:
603 SuperstructureCANWriter(::aos::EventLoop *event_loop)
604 : ::frc971::wpilib::LoopOutputHandler<superstructure::Output>(
605 event_loop, "/superstructure") {
606 event_loop->SetRuntimeRealtimePriority(
607 constants::Values::kSuperstructureCANWriterPriority);
608
609 event_loop->OnRun([this]() { WriteConfigs(); });
610 };
611
612 void HandleCANConfiguration(const frc971::CANConfiguration &configuration) {
Maxwell Henderson3772d282023-11-06 11:07:49 -0800613 roller_falcon_->PrintConfigs();
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800614 pivot_falcon_->PrintConfigs();
Ariv Diggi0af59c02023-10-07 13:15:39 -0700615 if (configuration.reapply()) {
616 WriteConfigs();
617 }
618 }
619
Maxwell Henderson3772d282023-11-06 11:07:49 -0800620 void set_roller_falcon(std::shared_ptr<Falcon> roller_falcon) {
621 roller_falcon_ = std::move(roller_falcon);
622 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700623
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800624 void set_pivot_falcon(std::shared_ptr<Falcon> pivot_falcon) {
625 pivot_falcon_ = std::move(pivot_falcon);
626 }
627
Maxwell Henderson3772d282023-11-06 11:07:49 -0800628 private:
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800629 void WriteConfigs() {
630 roller_falcon_->WriteRollerConfigs();
631 pivot_falcon_->WritePivotConfigs();
632 }
Maxwell Henderson3772d282023-11-06 11:07:49 -0800633
634 void Write(const superstructure::Output &output) override {
635 ctre::phoenix6::controls::DutyCycleOut roller_control(
636 SafeSpeed(-output.roller_voltage()));
637 roller_control.UpdateFreqHz = 0_Hz;
638 roller_control.EnableFOC = true;
639
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800640 ctre::phoenix6::controls::DutyCycleOut pivot_control(
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800641 SafeSpeed(output.pivot_joint_voltage()));
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800642 pivot_control.UpdateFreqHz = 0_Hz;
643 pivot_control.EnableFOC = true;
644
Maxwell Henderson3772d282023-11-06 11:07:49 -0800645 ctre::phoenix::StatusCode status =
646 roller_falcon_->talon()->SetControl(roller_control);
647
648 if (!status.IsOK()) {
649 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
650 status.GetName(), status.GetDescription());
651 }
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800652
653 status = pivot_falcon_->talon()->SetControl(pivot_control);
654
655 if (!status.IsOK()) {
656 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
657 status.GetName(), status.GetDescription());
658 }
Maxwell Henderson3772d282023-11-06 11:07:49 -0800659 }
Ariv Diggi0af59c02023-10-07 13:15:39 -0700660
661 void Stop() override {
662 AOS_LOG(WARNING, "Superstructure CAN output too old.\n");
663 ctre::phoenix6::controls::DutyCycleOut stop_command(0.0);
664 stop_command.UpdateFreqHz = 0_Hz;
665 stop_command.EnableFOC = true;
Maxwell Henderson3772d282023-11-06 11:07:49 -0800666
667 roller_falcon_->talon()->SetControl(stop_command);
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800668 pivot_falcon_->talon()->SetControl(stop_command);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700669 }
670
671 double SafeSpeed(double voltage) {
672 return (::aos::Clip(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
673 }
Maxwell Henderson3772d282023-11-06 11:07:49 -0800674
675 std::shared_ptr<Falcon> roller_falcon_;
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800676 std::shared_ptr<Falcon> pivot_falcon_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700677};
678
679class DrivetrainWriter : public ::frc971::wpilib::LoopOutputHandler<
680 ::frc971::control_loops::drivetrain::Output> {
681 public:
682 DrivetrainWriter(::aos::EventLoop *event_loop)
683 : ::frc971::wpilib::LoopOutputHandler<
684 ::frc971::control_loops::drivetrain::Output>(event_loop,
685 "/drivetrain") {
686 event_loop->SetRuntimeRealtimePriority(
687 constants::Values::kDrivetrainWriterPriority);
688
689 event_loop->OnRun([this]() { WriteConfigs(); });
690 }
691
692 void set_falcons(std::shared_ptr<Falcon> right_front,
693 std::shared_ptr<Falcon> right_back,
Ariv Diggi0af59c02023-10-07 13:15:39 -0700694 std::shared_ptr<Falcon> left_front,
Mirabel Wangf4e42672023-10-14 13:12:49 -0700695 std::shared_ptr<Falcon> left_back) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700696 right_front_ = std::move(right_front);
697 right_back_ = std::move(right_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700698 left_front_ = std::move(left_front);
699 left_back_ = std::move(left_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700700 }
701
702 void set_right_inverted(ctre::phoenix6::signals::InvertedValue invert) {
703 right_inverted_ = invert;
704 }
705
706 void set_left_inverted(ctre::phoenix6::signals::InvertedValue invert) {
707 left_inverted_ = invert;
708 }
709
710 void HandleCANConfiguration(const frc971::CANConfiguration &configuration) {
Mirabel Wangf4e42672023-10-14 13:12:49 -0700711 for (auto falcon : {right_front_, right_back_, left_front_, left_back_}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700712 falcon->PrintConfigs();
713 }
714 if (configuration.reapply()) {
715 WriteConfigs();
716 }
717 }
718
719 private:
720 void WriteConfigs() {
Mirabel Wangf4e42672023-10-14 13:12:49 -0700721 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700722 falcon->WriteConfigs(right_inverted_);
723 }
724
Mirabel Wangf4e42672023-10-14 13:12:49 -0700725 for (auto falcon : {left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700726 falcon->WriteConfigs(left_inverted_);
727 }
728 }
729
730 void Write(
731 const ::frc971::control_loops::drivetrain::Output &output) override {
732 ctre::phoenix6::controls::DutyCycleOut left_control(
733 SafeSpeed(output.left_voltage()));
734 left_control.UpdateFreqHz = 0_Hz;
735 left_control.EnableFOC = true;
736
737 ctre::phoenix6::controls::DutyCycleOut right_control(
738 SafeSpeed(output.right_voltage()));
739 right_control.UpdateFreqHz = 0_Hz;
740 right_control.EnableFOC = true;
741
Mirabel Wangf4e42672023-10-14 13:12:49 -0700742 for (auto falcon : {left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700743 ctre::phoenix::StatusCode status =
744 falcon->talon()->SetControl(left_control);
745
746 if (!status.IsOK()) {
747 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
748 status.GetName(), status.GetDescription());
749 }
750 }
751
Mirabel Wangf4e42672023-10-14 13:12:49 -0700752 for (auto falcon : {right_front_.get(), right_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700753 ctre::phoenix::StatusCode status =
754 falcon->talon()->SetControl(right_control);
755
756 if (!status.IsOK()) {
757 AOS_LOG(ERROR, "Failed to write control to falcon: %s: %s",
758 status.GetName(), status.GetDescription());
759 }
760 }
761 }
762
763 void Stop() override {
764 AOS_LOG(WARNING, "drivetrain output too old\n");
765 ctre::phoenix6::controls::DutyCycleOut stop_command(0.0);
766 stop_command.UpdateFreqHz = 0_Hz;
767 stop_command.EnableFOC = true;
768
Mirabel Wangf4e42672023-10-14 13:12:49 -0700769 for (auto falcon : {right_front_.get(), right_back_.get(),
770 left_front_.get(), left_back_.get()}) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700771 falcon->talon()->SetControl(stop_command);
772 }
773 }
774
775 double SafeSpeed(double voltage) {
776 return (::aos::Clip(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
777 }
778
779 ctre::phoenix6::signals::InvertedValue left_inverted_, right_inverted_;
Mirabel Wangf4e42672023-10-14 13:12:49 -0700780 std::shared_ptr<Falcon> right_front_, right_back_, left_front_, left_back_;
Ariv Diggi0af59c02023-10-07 13:15:39 -0700781};
782
783class WPILibRobot : public ::frc971::wpilib::WPILibRobotBase {
784 public:
785 ::std::unique_ptr<frc::Encoder> make_encoder(int index) {
786 return make_unique<frc::Encoder>(10 + index * 2, 11 + index * 2, false,
787 frc::Encoder::k4X);
788 }
789
790 void Run() override {
791 std::shared_ptr<const Values> values =
792 std::make_shared<const Values>(constants::MakeValues());
793
794 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
795 aos::configuration::ReadConfig("aos_config.json");
796
797 // Thread 1.
798 ::aos::ShmEventLoop joystick_sender_event_loop(&config.message());
799 ::frc971::wpilib::JoystickSender joystick_sender(
800 &joystick_sender_event_loop);
801 AddLoop(&joystick_sender_event_loop);
802
803 // Thread 2.
804 ::aos::ShmEventLoop pdp_fetcher_event_loop(&config.message());
805 ::frc971::wpilib::PDPFetcher pdp_fetcher(&pdp_fetcher_event_loop);
806 AddLoop(&pdp_fetcher_event_loop);
807
808 std::shared_ptr<frc::DigitalOutput> superstructure_reading =
809 make_unique<frc::DigitalOutput>(25);
810
811 std::vector<ctre::phoenix6::BaseStatusSignal *> signals_registry;
812 std::shared_ptr<Falcon> right_front =
813 std::make_shared<Falcon>(1, "Drivetrain Bus", &signals_registry);
814 std::shared_ptr<Falcon> right_back =
Maxwell Henderson3772d282023-11-06 11:07:49 -0800815 std::make_shared<Falcon>(0, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700816 std::shared_ptr<Falcon> left_front =
Maxwell Henderson3772d282023-11-06 11:07:49 -0800817 std::make_shared<Falcon>(2, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700818 std::shared_ptr<Falcon> left_back =
Maxwell Henderson3772d282023-11-06 11:07:49 -0800819 std::make_shared<Falcon>(3, "Drivetrain Bus", &signals_registry);
820 std::shared_ptr<Falcon> roller =
Ariv Diggi0af59c02023-10-07 13:15:39 -0700821 std::make_shared<Falcon>(5, "Drivetrain Bus", &signals_registry);
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800822 std::shared_ptr<Falcon> pivot =
823 std::make_shared<Falcon>(4, "Drivetrain Bus", &signals_registry);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700824
825 // Thread 3.
826 ::aos::ShmEventLoop can_sensor_reader_event_loop(&config.message());
827 can_sensor_reader_event_loop.set_name("CANSensorReader");
828 CANSensorReader can_sensor_reader(&can_sensor_reader_event_loop,
829 std::move(signals_registry));
830
Mirabel Wangf4e42672023-10-14 13:12:49 -0700831 can_sensor_reader.set_falcons(right_front, right_back, left_front,
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800832 left_back, roller, pivot);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700833
834 AddLoop(&can_sensor_reader_event_loop);
835
836 // Thread 4.
837 ::aos::ShmEventLoop sensor_reader_event_loop(&config.message());
838 SensorReader sensor_reader(&sensor_reader_event_loop, values,
839 &can_sensor_reader);
840 sensor_reader.set_pwm_trigger(true);
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800841 sensor_reader.set_drivetrain_left_encoder(make_encoder(4));
842 sensor_reader.set_drivetrain_right_encoder(make_encoder(5));
Ariv Diggi0af59c02023-10-07 13:15:39 -0700843 sensor_reader.set_superstructure_reading(superstructure_reading);
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800844 sensor_reader.set_yaw_rate_input(make_unique<frc::DigitalInput>(3));
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800845
Maxwell Henderson3772d282023-11-06 11:07:49 -0800846 sensor_reader.set_end_effector_cube_beam_break(
847 make_unique<frc::DigitalInput>(22));
Ariv Diggi0af59c02023-10-07 13:15:39 -0700848
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800849 sensor_reader.set_pivot_encoder(make_encoder(0));
850 sensor_reader.set_pivot_absolute_pwm(make_unique<frc::DigitalInput>(0));
851 sensor_reader.set_pivot_potentiometer(make_unique<frc::AnalogInput>(0));
Maxwell Henderson9435b5c2023-11-06 13:48:51 -0800852
Ariv Diggi0af59c02023-10-07 13:15:39 -0700853 AddLoop(&sensor_reader_event_loop);
854
855 // Thread 5.
856 // Set up CAN.
857 if (!FLAGS_ctre_diag_server) {
858 c_Phoenix_Diagnostics_SetSecondsToStart(-1);
859 c_Phoenix_Diagnostics_Dispose();
860 }
861
862 ctre::phoenix::platform::can::CANComm_SetRxSchedPriority(
863 constants::Values::kDrivetrainRxPriority, true, "Drivetrain Bus");
864 ctre::phoenix::platform::can::CANComm_SetTxSchedPriority(
865 constants::Values::kDrivetrainTxPriority, true, "Drivetrain Bus");
866
867 ::aos::ShmEventLoop can_output_event_loop(&config.message());
868 can_output_event_loop.set_name("CANOutputWriter");
869 DrivetrainWriter drivetrain_writer(&can_output_event_loop);
870
Mirabel Wangf4e42672023-10-14 13:12:49 -0700871 drivetrain_writer.set_falcons(right_front, right_back, left_front,
872 left_back);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700873 drivetrain_writer.set_right_inverted(
Ariv Diggi0af59c02023-10-07 13:15:39 -0700874 ctre::phoenix6::signals::InvertedValue::CounterClockwise_Positive);
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800875 drivetrain_writer.set_left_inverted(
876 ctre::phoenix6::signals::InvertedValue::Clockwise_Positive);
877
878 SuperstructureCANWriter superstructure_can_writer(&can_output_event_loop);
879 superstructure_can_writer.set_roller_falcon(roller);
880 superstructure_can_writer.set_pivot_falcon(pivot);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700881
882 can_output_event_loop.MakeWatcher(
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800883 "/roborio", [&drivetrain_writer, &superstructure_can_writer](
884 const frc971::CANConfiguration &configuration) {
Ariv Diggi0af59c02023-10-07 13:15:39 -0700885 drivetrain_writer.HandleCANConfiguration(configuration);
Filip Kujawa35b5aad2023-11-14 21:53:19 -0800886 superstructure_can_writer.HandleCANConfiguration(configuration);
Ariv Diggi0af59c02023-10-07 13:15:39 -0700887 });
888
889 AddLoop(&can_output_event_loop);
890
Ariv Diggi0af59c02023-10-07 13:15:39 -0700891 RunLoops();
892 }
893};
894
895} // namespace wpilib
896} // namespace y2023_bot3
897
Maxwell Henderson1c0843c2023-12-22 16:20:59 -0800898AOS_ROBOT_CLASS(::y2023_bot3::wpilib::WPILibRobot);