blob: 587718b6ae31352e08536ac5096180df60158759 [file] [log] [blame]
Niko Sohmers3860f8a2024-01-12 21:05:19 -08001#include <unistd.h>
2
3#include <array>
4#include <chrono>
5#include <cinttypes>
Niko Sohmers3860f8a2024-01-12 21:05:19 -08006#include <cstdio>
7#include <cstring>
8#include <functional>
9#include <memory>
10#include <mutex>
11#include <thread>
12
Niko Sohmers3860f8a2024-01-12 21:05:19 -080013#include "frc971/wpilib/ahal/AnalogInput.h"
Niko Sohmers3860f8a2024-01-12 21:05:19 -080014#include "frc971/wpilib/ahal/DriverStation.h"
15#include "frc971/wpilib/ahal/Encoder.h"
Niko Sohmers3860f8a2024-01-12 21:05:19 -080016#include "frc971/wpilib/ahal/TalonFX.h"
17#include "frc971/wpilib/ahal/VictorSP.h"
18#undef ERROR
19
20#include "ctre/phoenix/cci/Diagnostics_CCI.h"
Niko Sohmers3860f8a2024-01-12 21:05:19 -080021
22#include "aos/commonmath.h"
23#include "aos/containers/sized_array.h"
24#include "aos/events/event_loop.h"
25#include "aos/events/shm_event_loop.h"
26#include "aos/init.h"
27#include "aos/logging/logging.h"
28#include "aos/realtime.h"
29#include "aos/time/time.h"
30#include "aos/util/log_interval.h"
31#include "aos/util/phased_loop.h"
32#include "aos/util/wrapping_counter.h"
33#include "frc971/autonomous/auto_mode_generated.h"
34#include "frc971/can_configuration_generated.h"
Maxwell Hendersonf75800f2024-01-12 19:52:05 -080035#include "frc971/control_loops/drivetrain/drivetrain_can_position_static.h"
Niko Sohmers3860f8a2024-01-12 21:05:19 -080036#include "frc971/control_loops/drivetrain/drivetrain_position_generated.h"
37#include "frc971/input/robot_state_generated.h"
38#include "frc971/queues/gyro_generated.h"
Niko Sohmers3860f8a2024-01-12 21:05:19 -080039#include "frc971/wpilib/buffered_pcm.h"
40#include "frc971/wpilib/buffered_solenoid.h"
Maxwell Hendersonf75800f2024-01-12 19:52:05 -080041#include "frc971/wpilib/can_drivetrain_writer.h"
42#include "frc971/wpilib/can_sensor_reader.h"
Niko Sohmers3860f8a2024-01-12 21:05:19 -080043#include "frc971/wpilib/dma.h"
Niko Sohmers3860f8a2024-01-12 21:05:19 -080044#include "frc971/wpilib/encoder_and_potentiometer.h"
45#include "frc971/wpilib/joystick_sender.h"
46#include "frc971/wpilib/logging_generated.h"
47#include "frc971/wpilib/loop_output_handler.h"
48#include "frc971/wpilib/pdp_fetcher.h"
49#include "frc971/wpilib/sensor_reader.h"
Maxwell Hendersonf75800f2024-01-12 19:52:05 -080050#include "frc971/wpilib/talonfx.h"
Niko Sohmers3860f8a2024-01-12 21:05:19 -080051#include "frc971/wpilib/wpilib_robot_base.h"
52#include "y2024/constants.h"
53#include "y2024/control_loops/superstructure/superstructure_output_generated.h"
54#include "y2024/control_loops/superstructure/superstructure_position_generated.h"
55
56DEFINE_bool(ctre_diag_server, false,
57 "If true, enable the diagnostics server for interacting with "
58 "devices on the CAN bus using Phoenix Tuner");
59
60using ::aos::monotonic_clock;
61using ::frc971::CANConfiguration;
Maxwell Hendersonf75800f2024-01-12 19:52:05 -080062using ::frc971::control_loops::drivetrain::CANPositionStatic;
63using ::frc971::wpilib::TalonFX;
Niko Sohmers3860f8a2024-01-12 21:05:19 -080064using ::y2024::constants::Values;
65namespace superstructure = ::y2024::control_loops::superstructure;
66namespace drivetrain = ::y2024::control_loops::drivetrain;
67namespace chrono = ::std::chrono;
68using std::make_unique;
69
70namespace y2024 {
71namespace wpilib {
72namespace {
73
74constexpr double kMaxBringupPower = 12.0;
75
76// TODO(Brian): Fix the interpretation of the result of GetRaw here and in the
77// DMA stuff and then removing the * 2.0 in *_translate.
78// The low bit is direction.
79
80double drivetrain_velocity_translate(double in) {
81 return (((1.0 / in) / Values::kDrivetrainCyclesPerRevolution()) *
82 (2.0 * M_PI)) *
83 Values::kDrivetrainEncoderRatio() *
84 control_loops::drivetrain::kWheelRadius;
85}
86
87constexpr double kMaxFastEncoderPulsesPerSecond = std::max({
88 Values::kMaxDrivetrainEncoderPulsesPerSecond(),
89});
90static_assert(kMaxFastEncoderPulsesPerSecond <= 1300000,
91 "fast encoders are too fast");
92
93} // namespace
94
Niko Sohmers3860f8a2024-01-12 21:05:19 -080095// Class to send position messages with sensor readings to our loops.
96class SensorReader : public ::frc971::wpilib::SensorReader {
97 public:
98 SensorReader(::aos::ShmEventLoop *event_loop,
99 std::shared_ptr<const Values> values)
100 : ::frc971::wpilib::SensorReader(event_loop),
101 values_(std::move(values)),
102 auto_mode_sender_(
103 event_loop->MakeSender<::frc971::autonomous::AutonomousMode>(
104 "/autonomous")),
105 superstructure_position_sender_(
106 event_loop->MakeSender<superstructure::Position>(
107 "/superstructure")),
108 drivetrain_position_sender_(
Maxwell Hendersonf75800f2024-01-12 19:52:05 -0800109 event_loop->MakeSender<
110 ::frc971::control_loops::drivetrain::PositionStatic>(
111 "/drivetrain")),
Niko Sohmers3860f8a2024-01-12 21:05:19 -0800112 gyro_sender_(event_loop->MakeSender<::frc971::sensors::GyroReading>(
113 "/drivetrain")){};
114 void Start() override { AddToDMA(&imu_yaw_rate_reader_); }
115
116 // Auto mode switches.
117 void set_autonomous_mode(int i, ::std::unique_ptr<frc::DigitalInput> sensor) {
118 autonomous_modes_.at(i) = ::std::move(sensor);
119 }
120
121 void set_yaw_rate_input(::std::unique_ptr<frc::DigitalInput> sensor) {
122 imu_yaw_rate_input_ = ::std::move(sensor);
123 imu_yaw_rate_reader_.set_input(imu_yaw_rate_input_.get());
124 }
125
126 void RunIteration() override {
127 {
128 auto builder = superstructure_position_sender_.MakeBuilder();
129
130 superstructure::Position::Builder position_builder =
131 builder.MakeBuilder<superstructure::Position>();
132 builder.CheckOk(builder.Send(position_builder.Finish()));
133 }
134
Maxwell Hendersonf75800f2024-01-12 19:52:05 -0800135 SendDrivetrainPosition(drivetrain_position_sender_.MakeStaticBuilder(),
136 drivetrain_velocity_translate,
137 constants::Values::DrivetrainEncoderToMeters, false,
138 false);
Niko Sohmers3860f8a2024-01-12 21:05:19 -0800139
140 {
141 auto builder = gyro_sender_.MakeBuilder();
142 ::frc971::sensors::GyroReading::Builder gyro_reading_builder =
143 builder.MakeBuilder<::frc971::sensors::GyroReading>();
144 // +/- 2000 deg / sec
145 constexpr double kMaxVelocity = 4000; // degrees / second
146 constexpr double kVelocityRadiansPerSecond =
147 kMaxVelocity / 360 * (2.0 * M_PI);
148
149 // Only part of the full range is used to prevent being 100% on or off.
150 constexpr double kScaledRangeLow = 0.1;
151 constexpr double kScaledRangeHigh = 0.9;
152
153 constexpr double kPWMFrequencyHz = 200;
154 double velocity_duty_cycle =
155 imu_yaw_rate_reader_.last_width() * kPWMFrequencyHz;
156
157 constexpr double kDutyCycleScale =
158 1 / (kScaledRangeHigh - kScaledRangeLow);
159 // scale from 0.1 - 0.9 to 0 - 1
160 double rescaled_velocity_duty_cycle =
161 (velocity_duty_cycle - kScaledRangeLow) * kDutyCycleScale;
162
163 if (!std::isnan(rescaled_velocity_duty_cycle)) {
164 gyro_reading_builder.add_velocity((rescaled_velocity_duty_cycle - 0.5) *
165 kVelocityRadiansPerSecond);
166 }
167 builder.CheckOk(builder.Send(gyro_reading_builder.Finish()));
168 }
169
170 {
171 auto builder = auto_mode_sender_.MakeBuilder();
172
173 uint32_t mode = 0;
174 for (size_t i = 0; i < autonomous_modes_.size(); ++i) {
175 if (autonomous_modes_[i] && autonomous_modes_[i]->Get()) {
176 mode |= 1 << i;
177 }
178 }
179
180 auto auto_mode_builder =
181 builder.MakeBuilder<frc971::autonomous::AutonomousMode>();
182
183 auto_mode_builder.add_mode(mode);
184
185 builder.CheckOk(builder.Send(auto_mode_builder.Finish()));
186 }
187 }
188
189 private:
190 std::shared_ptr<const Values> values_;
191
192 aos::Sender<frc971::autonomous::AutonomousMode> auto_mode_sender_;
193 aos::Sender<superstructure::Position> superstructure_position_sender_;
Maxwell Hendersonf75800f2024-01-12 19:52:05 -0800194 aos::Sender<frc971::control_loops::drivetrain::PositionStatic>
Niko Sohmers3860f8a2024-01-12 21:05:19 -0800195 drivetrain_position_sender_;
196 ::aos::Sender<::frc971::sensors::GyroReading> gyro_sender_;
197
198 std::array<std::unique_ptr<frc::DigitalInput>, 2> autonomous_modes_;
199
200 std::unique_ptr<frc::DigitalInput> imu_yaw_rate_input_;
201
202 frc971::wpilib::DMAPulseWidthReader imu_yaw_rate_reader_;
203};
204
205class WPILibRobot : public ::frc971::wpilib::WPILibRobotBase {
206 public:
207 ::std::unique_ptr<frc::Encoder> make_encoder(int index) {
208 return make_unique<frc::Encoder>(10 + index * 2, 11 + index * 2, false,
209 frc::Encoder::k4X);
210 }
211
212 void Run() override {
213 std::shared_ptr<const Values> values =
214 std::make_shared<const Values>(constants::MakeValues());
215
216 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
217 aos::configuration::ReadConfig("aos_config.json");
218
219 // Thread 1.
220 ::aos::ShmEventLoop joystick_sender_event_loop(&config.message());
221 ::frc971::wpilib::JoystickSender joystick_sender(
222 &joystick_sender_event_loop);
223 AddLoop(&joystick_sender_event_loop);
224
225 // Thread 2.
226 ::aos::ShmEventLoop pdp_fetcher_event_loop(&config.message());
227 ::frc971::wpilib::PDPFetcher pdp_fetcher(&pdp_fetcher_event_loop);
228 AddLoop(&pdp_fetcher_event_loop);
229
230 // Thread 3.
231 ::aos::ShmEventLoop sensor_reader_event_loop(&config.message());
232 SensorReader sensor_reader(&sensor_reader_event_loop, values);
233 sensor_reader.set_pwm_trigger(true);
234 sensor_reader.set_drivetrain_left_encoder(make_encoder(1));
235 sensor_reader.set_drivetrain_right_encoder(make_encoder(0));
236 sensor_reader.set_yaw_rate_input(make_unique<frc::DigitalInput>(0));
237
238 AddLoop(&sensor_reader_event_loop);
239
240 // Thread 4.
241 // Set up CAN.
242 if (!FLAGS_ctre_diag_server) {
243 c_Phoenix_Diagnostics_SetSecondsToStart(-1);
244 c_Phoenix_Diagnostics_Dispose();
245 }
246
Maxwell Hendersonf75800f2024-01-12 19:52:05 -0800247 std::vector<ctre::phoenix6::BaseStatusSignal *> signals_registry;
248
249 std::shared_ptr<TalonFX> right_front = std::make_shared<TalonFX>(
250 0, false, "Drivetrain Bus", &signals_registry,
251 constants::Values::kDrivetrainStatorCurrentLimit(),
252 constants::Values::kDrivetrainSupplyCurrentLimit());
253 std::shared_ptr<TalonFX> right_back = std::make_shared<TalonFX>(
254 1, false, "Drivetrain Bus", &signals_registry,
255 constants::Values::kDrivetrainStatorCurrentLimit(),
256 constants::Values::kDrivetrainSupplyCurrentLimit());
257 std::shared_ptr<TalonFX> left_front = std::make_shared<TalonFX>(
258 2, false, "Drivetrain Bus", &signals_registry,
259 constants::Values::kDrivetrainStatorCurrentLimit(),
260 constants::Values::kDrivetrainSupplyCurrentLimit());
261 std::shared_ptr<TalonFX> left_back = std::make_shared<TalonFX>(
262 3, false, "Drivetrain Bus", &signals_registry,
263 constants::Values::kDrivetrainStatorCurrentLimit(),
264 constants::Values::kDrivetrainSupplyCurrentLimit());
265
Niko Sohmers3860f8a2024-01-12 21:05:19 -0800266 ctre::phoenix::platform::can::CANComm_SetRxSchedPriority(
267 constants::Values::kDrivetrainRxPriority, true, "Drivetrain Bus");
268 ctre::phoenix::platform::can::CANComm_SetTxSchedPriority(
269 constants::Values::kDrivetrainTxPriority, true, "Drivetrain Bus");
270
Maxwell Hendersonf75800f2024-01-12 19:52:05 -0800271 ::aos::ShmEventLoop can_sensor_reader_event_loop(&config.message());
272 can_sensor_reader_event_loop.set_name("CANSensorReader");
273
274 // Creating list of talonfx for CANSensorReader
275 std::vector<std::shared_ptr<TalonFX>> talonfxs;
276 for (auto talonfx : {right_front, right_back, left_front, left_back}) {
277 talonfxs.push_back(talonfx);
278 }
279
280 aos::Sender<CANPositionStatic> can_position_sender =
281 can_sensor_reader_event_loop.MakeSender<CANPositionStatic>(
282 "/drivetrain");
283
284 frc971::wpilib::CANSensorReader can_sensor_reader(
285 &can_sensor_reader_event_loop, std::move(signals_registry), talonfxs,
286 [talonfxs, &can_position_sender](ctre::phoenix::StatusCode status) {
287 aos::Sender<CANPositionStatic>::StaticBuilder builder =
288 can_position_sender.MakeStaticBuilder();
289
290 auto falcon_vector = builder->add_talonfxs();
291
292 for (auto talonfx : talonfxs) {
293 talonfx->SerializePosition(
294 falcon_vector->emplace_back(),
295 control_loops::drivetrain::kHighOutputRatio);
296 }
297
298 builder->set_timestamp(talonfxs.front()->GetTimestamp());
299 builder->set_status(static_cast<int>(status));
300
301 builder.CheckOk(builder.Send());
302 });
303
304 AddLoop(&can_sensor_reader_event_loop);
305
306 // Thread 5.
Niko Sohmers3860f8a2024-01-12 21:05:19 -0800307 ::aos::ShmEventLoop can_output_event_loop(&config.message());
308 can_output_event_loop.set_name("CANOutputWriter");
309
Maxwell Hendersonf75800f2024-01-12 19:52:05 -0800310 frc971::wpilib::CANDrivetrainWriter can_drivetrain_writer(
311 &can_output_event_loop);
Niko Sohmers3860f8a2024-01-12 21:05:19 -0800312
Maxwell Hendersonf75800f2024-01-12 19:52:05 -0800313 can_drivetrain_writer.set_talonfxs({right_front, right_back},
314 {left_front, left_back});
315
316 can_output_event_loop.MakeWatcher(
317 "/roborio", [&can_drivetrain_writer](
318 const frc971::CANConfiguration &configuration) {
319 can_drivetrain_writer.HandleCANConfiguration(configuration);
320 });
321
322 AddLoop(&can_output_event_loop);
Niko Sohmers3860f8a2024-01-12 21:05:19 -0800323
324 // Thread 6
325
326 RunLoops();
327 }
328};
329
330} // namespace wpilib
331} // namespace y2024
332
333AOS_ROBOT_CLASS(::y2024::wpilib::WPILibRobot);