blob: 036625656664f879615fc1a4e4d05e4de7e8d5c9 [file] [log] [blame]
Henry Speiser354d2782022-07-22 13:56:48 -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#include "frc971/wpilib/ahal/AnalogInput.h"
16#include "frc971/wpilib/ahal/Counter.h"
17#include "frc971/wpilib/ahal/DigitalGlitchFilter.h"
18#include "frc971/wpilib/ahal/DriverStation.h"
19#include "frc971/wpilib/ahal/Encoder.h"
20#include "frc971/wpilib/ahal/Servo.h"
21#include "frc971/wpilib/ahal/TalonFX.h"
22#include "frc971/wpilib/ahal/VictorSP.h"
23#undef ERROR
24
25#include "aos/commonmath.h"
26#include "aos/events/event_loop.h"
27#include "aos/events/shm_event_loop.h"
28#include "aos/init.h"
29#include "aos/logging/logging.h"
30#include "aos/realtime.h"
31#include "aos/time/time.h"
32#include "aos/util/log_interval.h"
33#include "aos/util/phased_loop.h"
34#include "aos/util/wrapping_counter.h"
35#include "ctre/phoenix/motorcontrol/can/TalonFX.h"
36#include "ctre/phoenix/motorcontrol/can/TalonSRX.h"
37#include "frc971/autonomous/auto_mode_generated.h"
38#include "frc971/control_loops/drivetrain/drivetrain_position_generated.h"
39#include "frc971/input/robot_state_generated.h"
40#include "frc971/queues/gyro_generated.h"
41#include "frc971/wpilib/ADIS16448.h"
42#include "frc971/wpilib/buffered_pcm.h"
43#include "frc971/wpilib/buffered_solenoid.h"
44#include "frc971/wpilib/dma.h"
45#include "frc971/wpilib/drivetrain_writer.h"
46#include "frc971/wpilib/encoder_and_potentiometer.h"
47#include "frc971/wpilib/joystick_sender.h"
48#include "frc971/wpilib/logging_generated.h"
49#include "frc971/wpilib/loop_output_handler.h"
50#include "frc971/wpilib/pdp_fetcher.h"
51#include "frc971/wpilib/sensor_reader.h"
52#include "frc971/wpilib/wpilib_robot_base.h"
53#include "y2022_bot3/constants.h"
54#include "y2022_bot3/control_loops/superstructure/superstructure_output_generated.h"
55#include "y2022_bot3/control_loops/superstructure/superstructure_position_generated.h"
56
57using ::aos::monotonic_clock;
58using ::y2022_bot3::constants::Values;
59namespace superstructure = ::y2022_bot3::control_loops::superstructure;
60namespace chrono = ::std::chrono;
61using std::make_unique;
62
63namespace y2022_bot3 {
64namespace wpilib {
65namespace {
66
67constexpr double kMaxBringupPower = 12.0;
68
69// TODO(Brian): Fix the interpretation of the result of GetRaw here and in the
70// DMA stuff and then removing the * 2.0 in *_translate.
71// The low bit is direction.
72
73double drivetrain_velocity_translate(double in) {
74 return (((1.0 / in) / Values::kDrivetrainCyclesPerRevolution()) *
75 (2.0 * M_PI)) *
76 Values::kDrivetrainEncoderRatio() *
77 control_loops::drivetrain::kWheelRadius;
78}
79
80constexpr double kMaxFastEncoderPulsesPerSecond =
81 Values::kMaxDrivetrainEncoderPulsesPerSecond();
82static_assert(kMaxFastEncoderPulsesPerSecond <= 1300000,
83 "fast encoders are too fast");
84constexpr double kMaxMediumEncoderPulsesPerSecond = 0;
85
86static_assert(kMaxMediumEncoderPulsesPerSecond <= 400000,
87 "medium encoders are too fast");
88
89} // namespace
90
91// Class to send position messages with sensor readings to our loops.
92class SensorReader : public ::frc971::wpilib::SensorReader {
93 public:
94 SensorReader(::aos::ShmEventLoop *event_loop,
95 std::shared_ptr<const Values> values)
96 : ::frc971::wpilib::SensorReader(event_loop),
97 values_(std::move(values)),
98 auto_mode_sender_(
99 event_loop->MakeSender<::frc971::autonomous::AutonomousMode>(
100 "/autonomous")),
101 superstructure_position_sender_(
102 event_loop->MakeSender<superstructure::Position>(
103 "/superstructure")),
104 drivetrain_position_sender_(
105 event_loop
106 ->MakeSender<::frc971::control_loops::drivetrain::Position>(
107 "/drivetrain")),
108 gyro_sender_(event_loop->MakeSender<::frc971::sensors::GyroReading>(
109 "/drivetrain")) {
110 // Set to filter out anything shorter than 1/4 of the minimum pulse width
111 // we should ever see.
112 UpdateFastEncoderFilterHz(kMaxFastEncoderPulsesPerSecond);
113 UpdateMediumEncoderFilterHz(kMaxMediumEncoderPulsesPerSecond);
114 }
115
116 void Start() override {
117 // TODO(Ravago): Figure out why adding multiple DMA readers results in weird
118 // behavior
119 // AddToDMA(&imu_heading_reader_);
120 AddToDMA(&imu_yaw_rate_reader_);
121 }
122
123 // Auto mode switches.
124 void set_autonomous_mode(int i, ::std::unique_ptr<frc::DigitalInput> sensor) {
125 autonomous_modes_.at(i) = ::std::move(sensor);
126 }
127
128 void set_heading_input(::std::unique_ptr<frc::DigitalInput> sensor) {
129 imu_heading_input_ = ::std::move(sensor);
130 imu_heading_reader_.set_input(imu_heading_input_.get());
131 }
132
133 void set_yaw_rate_input(::std::unique_ptr<frc::DigitalInput> sensor) {
134 imu_yaw_rate_input_ = ::std::move(sensor);
135 imu_yaw_rate_reader_.set_input(imu_yaw_rate_input_.get());
136 }
137
138 void RunIteration() override {
139 {
140 auto builder = superstructure_position_sender_.MakeBuilder();
141 superstructure::Position::Builder position_builder =
142 builder.MakeBuilder<superstructure::Position>();
143 builder.CheckOk(builder.Send(position_builder.Finish()));
144 }
145
146 {
147 auto builder = drivetrain_position_sender_.MakeBuilder();
148 frc971::control_loops::drivetrain::Position::Builder drivetrain_builder =
149 builder.MakeBuilder<frc971::control_loops::drivetrain::Position>();
150 drivetrain_builder.add_left_encoder(
151 constants::Values::DrivetrainEncoderToMeters(
152 drivetrain_left_encoder_->GetRaw()));
153 drivetrain_builder.add_left_speed(
154 drivetrain_velocity_translate(drivetrain_left_encoder_->GetPeriod()));
155
156 drivetrain_builder.add_right_encoder(
157 -constants::Values::DrivetrainEncoderToMeters(
158 drivetrain_right_encoder_->GetRaw()));
159 drivetrain_builder.add_right_speed(-drivetrain_velocity_translate(
160 drivetrain_right_encoder_->GetPeriod()));
161
162 builder.CheckOk(builder.Send(drivetrain_builder.Finish()));
163 }
164
165 {
166 auto builder = gyro_sender_.MakeBuilder();
167 ::frc971::sensors::GyroReading::Builder gyro_reading_builder =
168 builder.MakeBuilder<::frc971::sensors::GyroReading>();
169 // +/- 2000 deg / sec
170 constexpr double kMaxVelocity = 4000; // degrees / second
171 constexpr double kVelocityRadiansPerSecond =
172 kMaxVelocity / 360 * (2.0 * M_PI);
173
174 // Only part of the full range is used to prevent being 100% on or off.
175 constexpr double kScaledRangeLow = 0.1;
176 constexpr double kScaledRangeHigh = 0.9;
177
178 constexpr double kPWMFrequencyHz = 200;
179 double heading_duty_cycle =
180 imu_heading_reader_.last_width() * kPWMFrequencyHz;
181 double velocity_duty_cycle =
182 imu_yaw_rate_reader_.last_width() * kPWMFrequencyHz;
183
184 constexpr double kDutyCycleScale =
185 1 / (kScaledRangeHigh - kScaledRangeLow);
186 // scale from 0.1 - 0.9 to 0 - 1
187 double rescaled_heading_duty_cycle =
188 (heading_duty_cycle - kScaledRangeLow) * kDutyCycleScale;
189 double rescaled_velocity_duty_cycle =
190 (velocity_duty_cycle - kScaledRangeLow) * kDutyCycleScale;
191
192 if (!std::isnan(rescaled_heading_duty_cycle)) {
193 gyro_reading_builder.add_angle(rescaled_heading_duty_cycle *
194 (2.0 * M_PI));
195 }
196 if (!std::isnan(rescaled_velocity_duty_cycle)) {
197 gyro_reading_builder.add_velocity((rescaled_velocity_duty_cycle - 0.5) *
198 kVelocityRadiansPerSecond);
199 }
200 builder.CheckOk(builder.Send(gyro_reading_builder.Finish()));
201 }
202
203 {
204 auto builder = auto_mode_sender_.MakeBuilder();
205
206 uint32_t mode = 0;
207 for (size_t i = 0; i < autonomous_modes_.size(); ++i) {
208 if (autonomous_modes_[i] && autonomous_modes_[i]->Get()) {
209 mode |= 1 << i;
210 }
211 }
212
213 auto auto_mode_builder =
214 builder.MakeBuilder<frc971::autonomous::AutonomousMode>();
215
216 auto_mode_builder.add_mode(mode);
217
218 builder.CheckOk(builder.Send(auto_mode_builder.Finish()));
219 }
220 }
221
222 private:
223 std::shared_ptr<const Values> values_;
224
225 aos::Sender<frc971::autonomous::AutonomousMode> auto_mode_sender_;
226 aos::Sender<superstructure::Position> superstructure_position_sender_;
227 aos::Sender<frc971::control_loops::drivetrain::Position>
228 drivetrain_position_sender_;
229 ::aos::Sender<::frc971::sensors::GyroReading> gyro_sender_;
230
231 std::array<std::unique_ptr<frc::DigitalInput>, 2> autonomous_modes_;
232
233 std::unique_ptr<frc::DigitalInput> imu_heading_input_, imu_yaw_rate_input_;
234
235 frc971::wpilib::DMAPulseWidthReader imu_heading_reader_, imu_yaw_rate_reader_;
236};
237
238class SuperstructureWriter
239 : public ::frc971::wpilib::LoopOutputHandler<superstructure::Output> {
240 public:
241 SuperstructureWriter(aos::EventLoop *event_loop)
242 : frc971::wpilib::LoopOutputHandler<superstructure::Output>(
243 event_loop, "/superstructure") {}
244
245 private:
246 void Stop() override { AOS_LOG(WARNING, "Superstructure output too old.\n"); }
247
248 void Write(const superstructure::Output &output) override { (void)output; }
249
250 static void WriteCan(const double voltage,
251 ::ctre::phoenix::motorcontrol::can::TalonFX *falcon) {
252 falcon->Set(
253 ctre::phoenix::motorcontrol::ControlMode::PercentOutput,
254 std::clamp(voltage, -kMaxBringupPower, kMaxBringupPower) / 12.0);
255 }
256
257 template <typename T>
258 static void WritePwm(const double voltage, T *motor) {
259 motor->SetSpeed(std::clamp(voltage, -kMaxBringupPower, kMaxBringupPower) /
260 12.0);
261 }
262};
263
264class WPILibRobot : public ::frc971::wpilib::WPILibRobotBase {
265 public:
266 ::std::unique_ptr<frc::Encoder> make_encoder(int index) {
267 return make_unique<frc::Encoder>(10 + index * 2, 11 + index * 2, false,
268 frc::Encoder::k4X);
269 }
270
271 void Run() override {
272 std::shared_ptr<const Values> values =
273 std::make_shared<const Values>(constants::MakeValues());
274
275 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
276 aos::configuration::ReadConfig("aos_config.json");
277
278 // Thread 1.
279 ::aos::ShmEventLoop joystick_sender_event_loop(&config.message());
280 ::frc971::wpilib::JoystickSender joystick_sender(
281 &joystick_sender_event_loop);
282 AddLoop(&joystick_sender_event_loop);
283
284 // Thread 2.
285 ::aos::ShmEventLoop pdp_fetcher_event_loop(&config.message());
286 ::frc971::wpilib::PDPFetcher pdp_fetcher(&pdp_fetcher_event_loop);
287 AddLoop(&pdp_fetcher_event_loop);
288
289 // Thread 3.
290 ::aos::ShmEventLoop sensor_reader_event_loop(&config.message());
291 SensorReader sensor_reader(&sensor_reader_event_loop, values);
292 sensor_reader.set_pwm_trigger(true);
293 sensor_reader.set_drivetrain_left_encoder(make_encoder(1));
294 sensor_reader.set_drivetrain_right_encoder(make_encoder(0));
295
296 sensor_reader.set_heading_input(make_unique<frc::DigitalInput>(9));
297 sensor_reader.set_yaw_rate_input(make_unique<frc::DigitalInput>(8));
298
299 AddLoop(&sensor_reader_event_loop);
300
301 // Thread 4.
302 ::aos::ShmEventLoop output_event_loop(&config.message());
303 ::frc971::wpilib::DrivetrainWriter drivetrain_writer(&output_event_loop);
304 drivetrain_writer.set_left_controller0(
305 ::std::unique_ptr<::frc::VictorSP>(new ::frc::VictorSP(0)), false);
306 drivetrain_writer.set_right_controller0(
307 ::std::unique_ptr<::frc::VictorSP>(new ::frc::VictorSP(1)), true);
308
309 SuperstructureWriter superstructure_writer(&output_event_loop);
310
311 AddLoop(&output_event_loop);
312
313 // Thread 5.
314 RunLoops();
315 }
316};
317
318} // namespace wpilib
319} // namespace y2022_bot3
320
321AOS_ROBOT_CLASS(::y2022_bot3::wpilib::WPILibRobot);