blob: 3a666f9f25664bab1f5be49e25612ad161fb3cbc [file] [log] [blame]
Nathan Leongdd728002024-02-03 15:26:53 -08001#include "frc971/control_loops/catapult/mpc_problem_generator.h"
2// A class to hold all the state needed to manage the catapult MPC solvers for
3// repeated shots.
4//
5// The solver may take a couple of cycles to get everything converged and ready.
6// The flow is as follows:
7// 1) Reset() the state for the new problem.
8// 2) Update to the current state with SetState()
9// 3) Call Solve(). This will return true if it is ready to be executed, false
10// if it needs more iterations to fully converge.
11// 4) Next() returns the current optimal control output and advances the
12// pointers to the next problem.
13// 5) Go back to 2 for the next cycle.
14
15namespace frc971 {
16namespace control_loops {
17namespace catapult {
18
19class CatapultController {
20 public:
21 CatapultController(StateFeedbackPlant<2, 1, 1> plant, size_t horizon);
22
23 // Starts back over at the first controller.
24 void Reset();
25
26 // Updates our current and final states for the current controller.
27 void SetState(Eigen::Matrix<double, 2, 1> X_initial,
28 Eigen::Matrix<double, 2, 1> X_final);
29
30 // Solves! Returns true if the solution converged and osqp was happy.
31 bool Solve();
32
33 // Returns the time in seconds it last took Solve to run.
34 double solve_time() const { return solve_time_; }
35
36 // Returns the horizon of the current controller.
37 size_t current_horizon() const {
38 if (current_controller_ >= problems_.size()) {
39 return 0u;
40 } else {
41 return problems_[current_controller_]->horizon();
42 }
43 }
44
45 // Returns the controller value if there is a controller to run, or nullopt if
46 // we finished the last controller. Advances the controller pointer to the
47 // next controller and warms up the next controller.
48 std::optional<double> Next();
49
50 // Returns true if Next has been called and a controller has been used. Reset
51 // starts over.
52 bool started() const { return current_controller_ != 0u; }
53
54 private:
55 CatapultProblemGenerator generator_;
56
57 std::vector<std::unique_ptr<MPCProblem>> problems_;
58
59 size_t current_controller_ = 0;
60 double solve_time_ = 0.0;
61};
62
63} // namespace catapult
64} // namespace control_loops
65} // namespace frc971