Maxwell Henderson | 0169d11 | 2023-12-25 13:15:16 -0800 | [diff] [blame^] | 1 | #include <map> |
| 2 | #include <string_view> |
| 3 | |
| 4 | #include "frc971/can_configuration_generated.h" |
| 5 | #include "frc971/wpilib/falcon.h" |
| 6 | #include "frc971/wpilib/loop_output_handler.h" |
| 7 | |
| 8 | namespace frc971 { |
| 9 | namespace wpilib { |
| 10 | |
| 11 | /// This class uses a callback whenever it writes so that the caller can use any |
| 12 | /// flatbuffer to write to the falcon. |
| 13 | template <typename T> |
| 14 | class GenericCANWriter : public LoopOutputHandler<T> { |
| 15 | public: |
| 16 | GenericCANWriter( |
| 17 | ::aos::EventLoop *event_loop, |
| 18 | std::function< |
| 19 | void(const T &output, |
| 20 | std::map<std::string, std::shared_ptr<Falcon>> falcon_map)> |
| 21 | write_callback) |
| 22 | : LoopOutputHandler<T>(event_loop, "/superstructure"), |
| 23 | write_callback_(write_callback) { |
| 24 | event_loop->SetRuntimeRealtimePriority(kGenericCANWriterPriority); |
| 25 | |
| 26 | event_loop->OnRun([this]() { WriteConfigs(); }); |
| 27 | } |
| 28 | |
| 29 | void HandleCANConfiguration(const CANConfiguration &configuration) { |
| 30 | for (auto &[_, falcon] : falcon_map_) { |
| 31 | falcon->PrintConfigs(); |
| 32 | } |
| 33 | |
| 34 | if (configuration.reapply()) { |
| 35 | WriteConfigs(); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | void add_falcon(std::string_view name, std::shared_ptr<Falcon> falcon) { |
| 40 | falcon_map_.insert({name, std::move(falcon)}); |
| 41 | } |
| 42 | |
| 43 | static constexpr int kGenericCANWriterPriority = 35; |
| 44 | |
| 45 | private: |
| 46 | void WriteConfigs() { |
| 47 | for (auto &[_, falcon] : falcon_map_) { |
| 48 | falcon->WriteConfigs(); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | void Write(const T &output) override { write_callback_(output, falcon_map_); } |
| 53 | |
| 54 | void Stop() override { |
| 55 | AOS_LOG(WARNING, "Generic CAN output too old.\n"); |
| 56 | for (auto &[_, falcon] : falcon_map_) { |
| 57 | falcon->WriteVoltage(0); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // Maps each name to a falcon to let the caller retreive them when writing |
| 62 | std::map<std::string_view, std::shared_ptr<Falcon>> falcon_map_; |
| 63 | |
| 64 | std::function<void(const T &output, |
| 65 | std::map<std::string, std::shared_ptr<Falcon>> falcon_map)> |
| 66 | write_callback_; |
| 67 | }; |
| 68 | |
| 69 | } // namespace wpilib |
| 70 | } // namespace frc971 |