Added indexer support, with stall detection.

Re-tuned some other loops while I was learning more about the indexer.

Change-Id: I893f1f273b31357ae9137601ca27322fc3b09d98
diff --git a/y2017/control_loops/python/hood.py b/y2017/control_loops/python/hood.py
index 3e71a0f..8684c98 100755
--- a/y2017/control_loops/python/hood.py
+++ b/y2017/control_loops/python/hood.py
@@ -112,7 +112,7 @@
 
     glog.debug('K %s', repr(self.K))
     glog.debug('Poles are %s',
-              repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
+               repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
 
     q_pos = 0.10
     q_vel = 1.65
diff --git a/y2017/control_loops/python/indexer.py b/y2017/control_loops/python/indexer.py
index 01d9797..6b1d59a 100755
--- a/y2017/control_loops/python/indexer.py
+++ b/y2017/control_loops/python/indexer.py
@@ -13,6 +13,8 @@
 
 gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
 
+gflags.DEFINE_bool('stall', False, 'If true, stall the indexer.')
+
 class VelocityIndexer(control_loop.ControlLoop):
   def __init__(self, name='VelocityIndexer'):
     super(VelocityIndexer, self).__init__(name)
@@ -74,8 +76,11 @@
     self.A, self.B = self.ContinuousToDiscrete(
         self.A_continuous, self.B_continuous, self.dt)
 
-    self.PlaceControllerPoles([.82])
-    glog.debug(repr(self.K))
+    self.PlaceControllerPoles([.80])
+    glog.debug('K: %s', repr(self.K))
+
+    glog.debug('Poles are %s',
+               repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
 
     self.PlaceObserverPoles([0.3])
 
@@ -127,7 +132,7 @@
 
 
 class IntegralIndexer(Indexer):
-  def __init__(self, name="IntegralIndexer"):
+  def __init__(self, name="IntegralIndexer", voltage_error_noise=None):
     super(IntegralIndexer, self).__init__(name=name)
 
     self.A_continuous_unaugmented = self.A_continuous
@@ -147,9 +152,12 @@
     self.A, self.B = self.ContinuousToDiscrete(
         self.A_continuous, self.B_continuous, self.dt)
 
-    q_pos = 2.0
-    q_vel = 0.001
-    q_voltage = 10.0
+    q_pos = 0.01
+    q_vel = 2.0
+    q_voltage = 0.4
+    if voltage_error_noise is not None:
+      q_voltage = voltage_error_noise
+
     self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
                            [0.0, (q_vel ** 2.0), 0.0],
                            [0.0, 0.0, (q_voltage ** 2.0)]])
@@ -179,6 +187,7 @@
     self.x = []
     self.v = []
     self.a = []
+    self.stall_ratio = []
     self.x_hat = []
     self.u = []
     self.offset = []
@@ -212,7 +221,10 @@
 
       if observer_indexer is not None:
         X_hat = observer_indexer.X_hat
+        observer_indexer.Y = indexer.Y
+        observer_indexer.CorrectObserver(numpy.matrix([[0.0]]))
         self.x_hat.append(observer_indexer.X_hat[1, 0])
+        self.offset.append(observer_indexer.X_hat[2, 0])
 
       ff_U = controller_indexer.Kff * (goal - observer_indexer.A * goal)
 
@@ -220,7 +232,6 @@
       U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
       self.x.append(indexer.X[0, 0])
 
-
       if self.v:
         last_v = self.v[-1]
       else:
@@ -229,17 +240,25 @@
       self.v.append(indexer.X[1, 0])
       self.a.append((self.v[-1] - last_v) / indexer.dt)
 
-      if observer_indexer is not None:
-        observer_indexer.Y = indexer.Y
-        observer_indexer.CorrectObserver(U)
-        self.offset.append(observer_indexer.X_hat[2, 0])
-
       applied_U = U.copy()
-      if i > 30:
-        applied_U += 2
-      indexer.Update(applied_U)
+      if i >= 40:
+        applied_U -= 2
+
+      if FLAGS.stall and i >= 40:
+        indexer.X[1, 0] = 0.0
+      else:
+        indexer.Update(applied_U)
 
       if observer_indexer is not None:
+        clipped_u = U[0, 0]
+        clip_u_value = 3.0
+        if clipped_u < 0:
+          clipped_u = min(clipped_u, -clip_u_value)
+        else:
+          clipped_u = max(clipped_u, clip_u_value)
+
+        self.stall_ratio.append(10 * (-self.offset[-1] / clipped_u))
+
         observer_indexer.PredictObserver(U)
 
       self.t.append(initial_t + i * indexer.dt)
@@ -254,6 +273,10 @@
     pylab.subplot(3, 1, 2)
     pylab.plot(self.t, self.u, label='u')
     pylab.plot(self.t, self.offset, label='voltage_offset')
+    pylab.plot(self.t, self.stall_ratio, label='stall_ratio')
+    pylab.plot(self.t,
+               [10.0 if x > 6.0 else 0.0 for x in self.stall_ratio],
+               label='is_stalled')
     pylab.legend()
 
     pylab.subplot(3, 1, 3)
@@ -278,8 +301,22 @@
   if FLAGS.plot:
     scenario_plotter.Plot()
 
-  if len(argv) != 5:
-    glog.fatal('Expected .h file name and .cc file name')
+  scenario_plotter = ScenarioPlotter()
+
+  indexer = Indexer()
+  indexer_controller = IntegralIndexer(voltage_error_noise=1.5)
+  observer_indexer = IntegralIndexer(voltage_error_noise=1.5)
+
+  initial_X = numpy.matrix([[0.0], [0.0]])
+  R = numpy.matrix([[0.0], [20.0], [0.0]])
+  scenario_plotter.run_test(indexer, goal=R, controller_indexer=indexer_controller,
+                            observer_indexer=observer_indexer, iterations=200)
+
+  if FLAGS.plot:
+    scenario_plotter.Plot()
+
+  if len(argv) != 7:
+    glog.fatal('Expected .h file name and .cc file names')
   else:
     namespaces = ['y2017', 'control_loops', 'superstructure', 'indexer']
     indexer = Indexer('Indexer')
@@ -296,6 +333,11 @@
         'IntegralIndexer', [integral_indexer], namespaces=namespaces)
     integral_loop_writer.Write(argv[3], argv[4])
 
+    stuck_integral_indexer = IntegralIndexer('StuckIntegralIndexer', voltage_error_noise=1.5)
+    stuck_integral_loop_writer = control_loop.ControlLoopWriter(
+        'StuckIntegralIndexer', [stuck_integral_indexer], namespaces=namespaces)
+    stuck_integral_loop_writer.Write(argv[5], argv[6])
+
 
 if __name__ == '__main__':
   argv = FLAGS(sys.argv)
diff --git a/y2017/control_loops/python/shooter.py b/y2017/control_loops/python/shooter.py
index 25e4b24..64732b5 100755
--- a/y2017/control_loops/python/shooter.py
+++ b/y2017/control_loops/python/shooter.py
@@ -58,6 +58,10 @@
 
     self.PlaceControllerPoles([.90])
 
+    glog.debug('K %s', repr(self.K))
+    glog.debug('Poles are %s',
+               repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
+
     self.PlaceObserverPoles([0.3])
 
     self.U_max = numpy.matrix([[12.0]])
@@ -128,9 +132,9 @@
     self.A, self.B = self.ContinuousToDiscrete(
         self.A_continuous, self.B_continuous, self.dt)
 
-    q_pos = 2.0
-    q_vel = 0.001
-    q_voltage = 10.0
+    q_pos = 0.01
+    q_vel = 2.0
+    q_voltage = 0.2
     self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
                            [0.0, (q_vel ** 2.0), 0.0],
                            [0.0, 0.0, (q_voltage ** 2.0)]])
@@ -226,8 +230,6 @@
       self.t.append(initial_t + i * shooter.dt)
       self.u.append(U[0, 0])
 
-      glog.debug('Time: %f', self.t[-1])
-
   def Plot(self):
     pylab.subplot(3, 1, 1)
     pylab.plot(self.t, self.v, label='x')
diff --git a/y2017/control_loops/superstructure/BUILD b/y2017/control_loops/superstructure/BUILD
index 6c8291d..ebcc164 100644
--- a/y2017/control_loops/superstructure/BUILD
+++ b/y2017/control_loops/superstructure/BUILD
@@ -26,9 +26,10 @@
     ':superstructure_queue',
     '//aos/common/controls:control_loop',
     '//y2017/control_loops/superstructure/hood',
-    '//y2017/control_loops/superstructure/turret',
+    '//y2017/control_loops/superstructure/indexer',
     '//y2017/control_loops/superstructure/intake',
     '//y2017/control_loops/superstructure/shooter',
+    '//y2017/control_loops/superstructure/turret',
     '//y2017:constants',
   ],
 )
@@ -49,6 +50,7 @@
     '//frc971/control_loops:position_sensor_sim',
     '//frc971/control_loops:team_number_test_environment',
     '//y2017/control_loops/superstructure/hood:hood_plants',
+    '//y2017/control_loops/superstructure/indexer:indexer_plants',
     '//y2017/control_loops/superstructure/intake:intake_plants',
     '//y2017/control_loops/superstructure/shooter:shooter_plants',
     '//y2017/control_loops/superstructure/turret:turret_plants',
diff --git a/y2017/control_loops/superstructure/indexer/BUILD b/y2017/control_loops/superstructure/indexer/BUILD
index 3df0810..10b726f 100644
--- a/y2017/control_loops/superstructure/indexer/BUILD
+++ b/y2017/control_loops/superstructure/indexer/BUILD
@@ -9,6 +9,8 @@
     'indexer_plant.cc',
     'indexer_integral_plant.h',
     'indexer_integral_plant.cc',
+    'stuck_indexer_integral_plant.h',
+    'stuck_indexer_integral_plant.cc',
   ],
 )
 
@@ -18,12 +20,31 @@
   srcs = [
     'indexer_plant.cc',
     'indexer_integral_plant.cc',
+    'stuck_indexer_integral_plant.cc',
   ],
   hdrs = [
     'indexer_plant.h',
     'indexer_integral_plant.h',
+    'stuck_indexer_integral_plant.h',
   ],
   deps = [
     '//frc971/control_loops:state_feedback_loop',
   ],
 )
+
+cc_library(
+  name = 'indexer',
+  visibility = ['//visibility:public'],
+  srcs = [
+    'indexer.cc',
+  ],
+  hdrs = [
+    'indexer.h',
+  ],
+  deps = [
+    ':indexer_plants',
+    '//aos/common/controls:control_loop',
+    '//aos/common:math',
+    '//y2017/control_loops/superstructure:superstructure_queue',
+  ],
+)
diff --git a/y2017/control_loops/superstructure/indexer/indexer.cc b/y2017/control_loops/superstructure/indexer/indexer.cc
new file mode 100644
index 0000000..cab9864
--- /dev/null
+++ b/y2017/control_loops/superstructure/indexer/indexer.cc
@@ -0,0 +1,206 @@
+#include "y2017/control_loops/superstructure/indexer/indexer.h"
+
+#include <chrono>
+
+#include "aos/common/commonmath.h"
+#include "aos/common/controls/control_loops.q.h"
+#include "aos/common/logging/logging.h"
+#include "aos/common/logging/queue_logging.h"
+#include "aos/common/time.h"
+#include "y2017/control_loops/superstructure/indexer/indexer_integral_plant.h"
+#include "y2017/control_loops/superstructure/indexer/stuck_indexer_integral_plant.h"
+#include "y2017/control_loops/superstructure/superstructure.q.h"
+
+namespace y2017 {
+namespace control_loops {
+namespace superstructure {
+namespace indexer {
+
+namespace chrono = ::std::chrono;
+using ::aos::monotonic_clock;
+
+namespace {
+constexpr double kTolerance = 10.0;
+constexpr double kMinStuckVoltage = 3.0;
+constexpr chrono::milliseconds kForwardTimeout{500};
+constexpr chrono::milliseconds kReverseTimeout{500};
+constexpr chrono::milliseconds kReverseMinTimeout{100};
+}  // namespace
+
+// TODO(austin): Pseudo current limit?
+
+IndexerController::IndexerController()
+    : loop_(new StateFeedbackLoop<3, 1, 1>(
+          superstructure::indexer::MakeIntegralIndexerLoop())),
+      stuck_indexer_detector_(new StateFeedbackLoop<3, 1, 1>(
+          superstructure::indexer::MakeStuckIntegralIndexerLoop())) {
+  history_.fill(0);
+  Y_.setZero();
+  X_hat_current_.setZero();
+  stuck_indexer_X_hat_current_.setZero();
+}
+
+void IndexerController::set_goal(double angular_velocity_goal) {
+  loop_->mutable_next_R() << 0.0, angular_velocity_goal, 0.0;
+}
+
+void IndexerController::set_position(double current_position) {
+  // Update position in the model.
+  Y_ << current_position;
+
+  // Add the position to the history.
+  history_[history_position_] = current_position;
+  history_position_ = (history_position_ + 1) % kHistoryLength;
+
+  dt_velocity_ = (current_position - last_position_) /
+                 chrono::duration_cast<chrono::duration<double>>(
+                     ::aos::controls::kLoopFrequency)
+                     .count();
+  last_position_ = current_position;
+}
+
+double IndexerController::voltage() const { return loop_->U(0, 0); }
+
+double IndexerController::StuckRatio() const {
+  double applied_voltage = voltage();
+  if (applied_voltage < 0) {
+    applied_voltage = ::std::min(applied_voltage, -kMinStuckVoltage);
+  } else {
+    applied_voltage = ::std::max(applied_voltage, kMinStuckVoltage);
+  }
+  // Look at the ratio of the current controller power to the voltage_error
+  // term.  If our output is dominated by the voltage_error, then we are likely
+  // pretty stuck and should try reversing.
+  // We don't want to worry about dividing by zero, so keep the applied voltage
+  // away from 0 though a min/max.
+  return -stuck_indexer_X_hat_current_(2, 0) / applied_voltage;
+}
+bool IndexerController::IsStuck() const { return StuckRatio() > 0.6; }
+
+void IndexerController::Reset() { reset_ = true; }
+
+void IndexerController::PartialReset() { loop_->mutable_X_hat(2, 0) = 0.0; }
+
+void IndexerController::Update(bool disabled) {
+  loop_->mutable_R() = loop_->next_R();
+  if (::std::abs(loop_->R(1, 0)) < 0.1) {
+    // Kill power at low angular velocities.
+    disabled = true;
+  }
+
+  if (reset_) {
+    loop_->mutable_X_hat(0, 0) = Y_(0, 0);
+    loop_->mutable_X_hat(1, 0) = 0.0;
+    loop_->mutable_X_hat(2, 0) = 0.0;
+    stuck_indexer_detector_->mutable_X_hat(0, 0) = Y_(0, 0);
+    stuck_indexer_detector_->mutable_X_hat(1, 0) = 0.0;
+    stuck_indexer_detector_->mutable_X_hat(2, 0) = 0.0;
+    reset_ = false;
+  }
+
+  loop_->Correct(Y_);
+  stuck_indexer_detector_->Correct(Y_);
+
+  // Compute the oldest point in the history.
+  const int oldest_history_position =
+      ((history_position_ == 0) ? kHistoryLength : history_position_) - 1;
+
+  // Compute the distance moved over that time period.
+  average_angular_velocity_ =
+      (history_[oldest_history_position] - history_[history_position_]) /
+      (chrono::duration_cast<chrono::duration<double>>(
+           ::aos::controls::kLoopFrequency)
+           .count() *
+       static_cast<double>(kHistoryLength - 1));
+
+  // Ready if average angular velocity is close to the goal.
+  error_ = average_angular_velocity_ - loop_->next_R(1, 0);
+
+  ready_ = std::abs(error_) < kTolerance && loop_->next_R(1, 0) > 1.0;
+
+  X_hat_current_ = loop_->X_hat();
+  stuck_indexer_X_hat_current_ = stuck_indexer_detector_->X_hat();
+  position_error_ = X_hat_current_(0, 0) - Y_(0, 0);
+
+  loop_->Update(disabled);
+  stuck_indexer_detector_->UpdateObserver(loop_->U());
+}
+
+void IndexerController::SetStatus(IndexerStatus *status) {
+  status->avg_angular_velocity = average_angular_velocity_;
+
+  status->angular_velocity = X_hat_current_(1, 0);
+  status->ready = ready_;
+
+  status->voltage_error = X_hat_current_(2, 0);
+  status->stuck_voltage_error = stuck_indexer_X_hat_current_(2, 0);
+  status->position_error = position_error_;
+  status->instantaneous_velocity = dt_velocity_;
+
+  status->stuck = IsStuck();
+
+  status->stuck_ratio = StuckRatio();
+}
+
+void Indexer::Reset() { indexer_.Reset(); }
+
+void Indexer::Iterate(const control_loops::IndexerGoal *goal,
+                      const double *position, double *output,
+                      control_loops::IndexerStatus *status) {
+  if (goal) {
+    // Start indexing at the suggested velocity.
+    // If a "stuck" event is detected, reverse.  Stay reversed until either
+    // unstuck, or 0.5 seconds have elapsed.
+    // Then, start going forwards.  Don't detect stuck for 0.5 seconds.
+
+    monotonic_clock::time_point monotonic_now = monotonic_clock::now();
+    switch (state_) {
+      case State::RUNNING:
+        // Pass the velocity goal through.
+        indexer_.set_goal(goal->angular_velocity);
+        // If we are stuck and weren't just reversing, try reversing to unstick
+        // us.  We don't want to chatter back and forth too fast if reversing
+        // isn't working.
+        if (indexer_.IsStuck() &&
+            monotonic_now > kForwardTimeout + last_transition_time_) {
+          state_ = State::REVERSING;
+          last_transition_time_ = monotonic_now;
+          indexer_.Reset();
+        }
+        break;
+      case State::REVERSING:
+        // "Reverse" "slowly".
+        indexer_.set_goal(-5.0 * aos::sign(goal->angular_velocity));
+
+        // If we've timed out or are no longer stuck, try running again.
+        if ((!indexer_.IsStuck() &&
+             monotonic_now > last_transition_time_ + kReverseMinTimeout) ||
+            monotonic_now > kReverseTimeout + last_transition_time_) {
+          state_ = State::RUNNING;
+          last_transition_time_ = monotonic_now;
+
+          // Only reset if we got stuck going this way too.
+          if (monotonic_now > kReverseTimeout + last_transition_time_) {
+            indexer_.Reset();
+          }
+        }
+        break;
+    }
+  }
+
+  indexer_.set_position(*position);
+
+  indexer_.Update(output == nullptr);
+
+  indexer_.SetStatus(status);
+  status->state = static_cast<int32_t>(state_);
+
+  if (output) {
+    *output = indexer_.voltage();
+  }
+}
+
+}  // namespace indexer
+}  // namespace superstructure
+}  // namespace control_loops
+}  // namespace y2017
diff --git a/y2017/control_loops/superstructure/indexer/indexer.h b/y2017/control_loops/superstructure/indexer/indexer.h
new file mode 100644
index 0000000..5c1cc1b
--- /dev/null
+++ b/y2017/control_loops/superstructure/indexer/indexer.h
@@ -0,0 +1,121 @@
+#ifndef Y2017_CONTROL_LOOPS_INDEXER_INDEXER_H_
+#define Y2017_CONTROL_LOOPS_INDEXER_INDEXER_H_
+
+#include <memory>
+
+#include "aos/common/controls/control_loop.h"
+#include "aos/common/time.h"
+#include "frc971/control_loops/state_feedback_loop.h"
+
+#include "y2017/control_loops/superstructure/indexer/indexer_integral_plant.h"
+#include "y2017/control_loops/superstructure/superstructure.q.h"
+
+namespace y2017 {
+namespace control_loops {
+namespace superstructure {
+namespace indexer {
+
+class IndexerController {
+ public:
+  IndexerController();
+
+  // Sets the velocity goal in radians/sec
+  void set_goal(double angular_velocity_goal);
+  // Sets the current encoder position in radians
+  void set_position(double current_position);
+
+  // Populates the status structure.
+  void SetStatus(control_loops::IndexerStatus *status);
+
+  // Returns the control loop calculated voltage.
+  double voltage() const;
+
+  // Returns the instantaneous velocity.
+  double velocity() const { return loop_->X_hat(1, 0); }
+
+  double dt_velocity() const { return dt_velocity_; }
+
+  double error() const { return error_; }
+
+  // Returns true if the indexer is stuck.
+  bool IsStuck() const;
+  double StuckRatio() const;
+
+  // Executes the control loop for a cycle.
+  void Update(bool disabled);
+
+  // Resets the kalman filter and any other internal state.
+  void Reset();
+  // Resets the voltage error for when we reverse directions.
+  void PartialReset();
+
+ private:
+  // The current sensor measurement.
+  Eigen::Matrix<double, 1, 1> Y_;
+  // The control loop.
+  ::std::unique_ptr<StateFeedbackLoop<3, 1, 1>> loop_;
+
+  // The stuck indexer detector
+  ::std::unique_ptr<StateFeedbackLoop<3, 1, 1>> stuck_indexer_detector_;
+
+  // History array for calculating a filtered angular velocity.
+  static constexpr int kHistoryLength = 5;
+  ::std::array<double, kHistoryLength> history_;
+  ptrdiff_t history_position_ = 0;
+
+  double error_ = 0.0;
+  double dt_velocity_ = 0.0;
+  double last_position_ = 0.0;
+  double average_angular_velocity_ = 0.0;
+  double position_error_ = 0.0;
+
+  Eigen::Matrix<double, 3, 1> X_hat_current_;
+  Eigen::Matrix<double, 3, 1> stuck_indexer_X_hat_current_;
+
+  bool ready_ = false;
+  bool reset_ = false;
+
+  DISALLOW_COPY_AND_ASSIGN(IndexerController);
+};
+
+class Indexer {
+ public:
+  Indexer() {}
+
+  enum class State {
+    // The system is running correctly, no stuck condition detected.
+    RUNNING = 0,
+    // The system is reversing to unjam.
+    REVERSING = 1
+  };
+
+  // Iterates the indexer control loop one cycle.  position and status must
+  // never be nullptr.  goal can be nullptr if no goal exists, and output should
+  // be nullptr if disabled.
+  void Iterate(const control_loops::IndexerGoal *goal, const double *position,
+               double *output, control_loops::IndexerStatus *status);
+
+  // Sets the indexer up to reset the kalman filter next time Iterate is called.
+  void Reset();
+
+  State state() const { return state_; }
+
+ private:
+  IndexerController indexer_;
+
+  State state_ = State::RUNNING;
+
+  // The last time that we transitioned from RUNNING to REVERSING or the
+  // reverse.  Used to implement the timeouts.
+  ::aos::monotonic_clock::time_point last_transition_time_ =
+      ::aos::monotonic_clock::min_time;
+
+  DISALLOW_COPY_AND_ASSIGN(Indexer);
+};
+
+}  // namespace indexer
+}  // namespace superstructure
+}  // namespace control_loops
+}  // namespace y2017
+
+#endif  // Y2017_CONTROL_LOOPS_INDEXER_INDEXER_H_
diff --git a/y2017/control_loops/superstructure/shooter/shooter.cc b/y2017/control_loops/superstructure/shooter/shooter.cc
index d30a45c..c4d1630 100644
--- a/y2017/control_loops/superstructure/shooter/shooter.cc
+++ b/y2017/control_loops/superstructure/shooter/shooter.cc
@@ -90,9 +90,11 @@
     }
   }
   if (reset_) {
-    loop_->mutable_X_hat(2, 0) = 0.0;
-    loop_->mutable_X_hat(1, 0) = dt_velocity_;
     loop_->mutable_X_hat(0, 0) = Y_(0, 0);
+    // TODO(austin): This should be 0 for the WPILib reset since dt_velocity_
+    // will be rubbish.
+    loop_->mutable_X_hat(1, 0) = dt_velocity_;
+    loop_->mutable_X_hat(2, 0) = 0.0;
     reset_ = false;
   }
   last_ready_ = ready_;
diff --git a/y2017/control_loops/superstructure/superstructure.cc b/y2017/control_loops/superstructure/superstructure.cc
index 99de502..3cad298 100644
--- a/y2017/control_loops/superstructure/superstructure.cc
+++ b/y2017/control_loops/superstructure/superstructure.cc
@@ -27,6 +27,7 @@
     turret_.Reset();
     intake_.Reset();
     shooter_.Reset();
+    indexer_.Reset();
   }
 
   hood_.Iterate(unsafe_goal != nullptr ? &(unsafe_goal->hood) : nullptr,
@@ -46,6 +47,10 @@
                 &(position->theta_shooter),
                 output != nullptr ? &(output->voltage_shooter) : nullptr,
                 &(status->shooter));
+  indexer_.Iterate(unsafe_goal != nullptr ? &(unsafe_goal->indexer) : nullptr,
+                &(position->theta_indexer),
+                output != nullptr ? &(output->voltage_indexer) : nullptr,
+                &(status->indexer));
 }
 
 }  // namespace superstructure
diff --git a/y2017/control_loops/superstructure/superstructure.h b/y2017/control_loops/superstructure/superstructure.h
index 4dc99a5..575d1d3 100644
--- a/y2017/control_loops/superstructure/superstructure.h
+++ b/y2017/control_loops/superstructure/superstructure.h
@@ -6,10 +6,11 @@
 #include "aos/common/controls/control_loop.h"
 #include "frc971/control_loops/state_feedback_loop.h"
 #include "y2017/control_loops/superstructure/hood/hood.h"
-#include "y2017/control_loops/superstructure/turret/turret.h"
+#include "y2017/control_loops/superstructure/indexer/indexer.h"
 #include "y2017/control_loops/superstructure/intake/intake.h"
-#include "y2017/control_loops/superstructure/superstructure.q.h"
 #include "y2017/control_loops/superstructure/shooter/shooter.h"
+#include "y2017/control_loops/superstructure/superstructure.q.h"
+#include "y2017/control_loops/superstructure/turret/turret.h"
 
 namespace y2017 {
 namespace control_loops {
@@ -25,6 +26,8 @@
   const hood::Hood &hood() const { return hood_; }
   const turret::Turret &turret() const { return turret_; }
   const intake::Intake &intake() const { return intake_; }
+  const shooter::Shooter &shooter() const { return shooter_; }
+  const indexer::Indexer &indexer() const { return indexer_; }
 
  protected:
   virtual void RunIteration(
@@ -38,6 +41,7 @@
   turret::Turret turret_;
   intake::Intake intake_;
   shooter::Shooter shooter_;
+  indexer::Indexer indexer_;
 
   DISALLOW_COPY_AND_ASSIGN(Superstructure);
 };
diff --git a/y2017/control_loops/superstructure/superstructure.q b/y2017/control_loops/superstructure/superstructure.q
index 4a5edd8..49f93e5 100644
--- a/y2017/control_loops/superstructure/superstructure.q
+++ b/y2017/control_loops/superstructure/superstructure.q
@@ -64,8 +64,23 @@
   // directly so there isn't confusion on if the goal is up to date.
   bool ready;
 
-  // If true, we have aborted.
-  bool estopped;
+  // True if the indexer is stuck.
+  bool stuck;
+  float stuck_ratio;
+
+  // The state of the indexer state machine.
+  int32_t state;
+
+  // The estimated voltage error from the kalman filter in volts.
+  double voltage_error;
+  // The estimated voltage error from the stuck indexer kalman filter.
+  double stuck_voltage_error;
+
+  // The current velocity measured as delta x / delta t in radians/sec.
+  double instantaneous_velocity;
+
+  // The error between our measurement and expected measurement in radians.
+  double position_error;
 };
 
 struct ShooterStatus {
@@ -79,9 +94,6 @@
   // directly so there isn't confusion on if the goal is up to date.
   bool ready;
 
-  // If true, we have aborted.
-  bool estopped;
-
   // The estimated voltage error from the kalman filter in volts.
   double voltage_error;
 
diff --git a/y2017/control_loops/superstructure/superstructure_lib_test.cc b/y2017/control_loops/superstructure/superstructure_lib_test.cc
index 6f96066..c7cef55 100644
--- a/y2017/control_loops/superstructure/superstructure_lib_test.cc
+++ b/y2017/control_loops/superstructure/superstructure_lib_test.cc
@@ -12,6 +12,7 @@
 #include "gtest/gtest.h"
 #include "y2017/constants.h"
 #include "y2017/control_loops/superstructure/hood/hood_plant.h"
+#include "y2017/control_loops/superstructure/indexer/indexer_plant.h"
 #include "y2017/control_loops/superstructure/intake/intake_plant.h"
 #include "y2017/control_loops/superstructure/shooter/shooter_plant.h"
 #include "y2017/control_loops/superstructure/turret/turret_plant.h"
@@ -48,6 +49,25 @@
   double voltage_offset_ = 0.0;
 };
 
+class IndexerPlant : public StateFeedbackPlant<2, 1, 1> {
+ public:
+  explicit IndexerPlant(StateFeedbackPlant<2, 1, 1> &&other)
+      : StateFeedbackPlant<2, 1, 1>(::std::move(other)) {}
+
+  void CheckU() override {
+    EXPECT_LE(U(0, 0), U_max(0, 0) + 0.00001 + voltage_offset_);
+    EXPECT_GE(U(0, 0), U_min(0, 0) - 0.00001 + voltage_offset_);
+  }
+
+  double voltage_offset() const { return voltage_offset_; }
+  void set_voltage_offset(double voltage_offset) {
+    voltage_offset_ = voltage_offset;
+  }
+
+ private:
+  double voltage_offset_ = 0.0;
+};
+
 class HoodPlant : public StateFeedbackPlant<2, 1, 1> {
  public:
   explicit HoodPlant(StateFeedbackPlant<2, 1, 1> &&other)
@@ -125,6 +145,9 @@
         shooter_plant_(new ShooterPlant(::y2017::control_loops::superstructure::
                                             shooter::MakeShooterPlant())),
 
+        indexer_plant_(new IndexerPlant(::y2017::control_loops::superstructure::
+                                            indexer::MakeIndexerPlant())),
+
         superstructure_queue_(".y2017.control_loops.superstructure", 0xdeadbeef,
                               ".y2017.control_loops.superstructure.goal",
                               ".y2017.control_loops.superstructure.position",
@@ -182,6 +205,7 @@
     turret_pot_encoder_.GetSensorValues(&position->turret);
     intake_pot_encoder_.GetSensorValues(&position->intake);
     position->theta_shooter = shooter_plant_->Y(0, 0);
+    position->theta_indexer = indexer_plant_->Y(0, 0);
     position.Send();
   }
 
@@ -196,6 +220,8 @@
 
   double shooter_velocity() const { return shooter_plant_->X(1, 0); }
 
+  double indexer_velocity() const { return indexer_plant_->X(1, 0); }
+
   // Sets the difference between the commanded and applied powers.
   // This lets us test that the integrators work.
   void set_hood_power_error(double power_error) {
@@ -214,6 +240,15 @@
     shooter_plant_->set_voltage_offset(power_error);
   }
 
+  void set_indexer_voltage_offset(double power_error) {
+    indexer_plant_->set_voltage_offset(power_error);
+  }
+
+  // Triggers the indexer to freeze in position.
+  void set_freeze_indexer(bool freeze_indexer) {
+    freeze_indexer_ = freeze_indexer;
+  }
+
   // Simulates the superstructure for a single timestep.
   void Simulate() {
     EXPECT_TRUE(superstructure_queue_.output.FetchLatest());
@@ -262,10 +297,20 @@
         << superstructure_queue_.output->voltage_shooter +
                shooter_plant_->voltage_offset();
 
+    indexer_plant_->mutable_U()
+        << superstructure_queue_.output->voltage_indexer +
+               indexer_plant_->voltage_offset();
+
     hood_plant_->Update();
     turret_plant_->Update();
     intake_plant_->Update();
     shooter_plant_->Update();
+    if (freeze_indexer_) {
+      indexer_plant_->mutable_X(1, 0) = 0.0;
+    } else {
+      indexer_plant_->Update();
+    }
+
 
     const double angle_hood = hood_plant_->Y(0, 0);
     const double angle_turret = turret_plant_->Y(0, 0);
@@ -295,6 +340,9 @@
 
   ::std::unique_ptr<ShooterPlant> shooter_plant_;
 
+  ::std::unique_ptr<IndexerPlant> indexer_plant_;
+  bool freeze_indexer_ = false;
+
   SuperstructureQueue superstructure_queue_;
 };
 
@@ -332,6 +380,8 @@
     EXPECT_NEAR(superstructure_queue_.goal->intake.distance,
                 superstructure_plant_.intake_position(), 0.001);
 
+    // Check that the angular velocity, average angular velocity, and estimated
+    // angular velocity match when we are done for the shooter.
     EXPECT_NEAR(superstructure_queue_.goal->shooter.angular_velocity,
                 superstructure_queue_.status->shooter.angular_velocity, 0.1);
     EXPECT_NEAR(superstructure_queue_.goal->shooter.angular_velocity,
@@ -339,6 +389,16 @@
                 0.1);
     EXPECT_NEAR(superstructure_queue_.goal->shooter.angular_velocity,
                 superstructure_plant_.shooter_velocity(), 0.1);
+
+    // Check that the angular velocity, average angular velocity, and estimated
+    // angular velocity match when we are done for the indexer.
+    EXPECT_NEAR(superstructure_queue_.goal->indexer.angular_velocity,
+                superstructure_queue_.status->indexer.angular_velocity, 0.1);
+    EXPECT_NEAR(superstructure_queue_.goal->indexer.angular_velocity,
+                superstructure_queue_.status->indexer.avg_angular_velocity,
+                0.1);
+    EXPECT_NEAR(superstructure_queue_.goal->indexer.angular_velocity,
+                superstructure_plant_.indexer_velocity(), 0.1);
   }
 
   // Runs one iteration of the whole simulation.
@@ -658,7 +718,7 @@
 
 // Tests that the shooter spins up to speed and that it then spins down
 // without applying any power.
-TEST_F(SuperstructureTest, SpinUpAndDown) {
+TEST_F(SuperstructureTest, ShooterSpinUpAndDown) {
   // Spin up.
   {
     auto goal = superstructure_queue_.goal.MakeMessage();
@@ -666,6 +726,7 @@
     goal->turret.angle = constants::Values::kTurretRange.lower + 0.03;
     goal->intake.distance = constants::Values::kIntakeRange.lower + 0.03;
     goal->shooter.angular_velocity = 300.0;
+    goal->indexer.angular_velocity = 20.0;
     ASSERT_TRUE(goal.Send());
   }
 
@@ -679,6 +740,7 @@
     goal->turret.angle = constants::Values::kTurretRange.lower + 0.03;
     goal->intake.distance = constants::Values::kIntakeRange.lower + 0.03;
     goal->shooter.angular_velocity = 0.0;
+    goal->indexer.angular_velocity = 0.0;
     ASSERT_TRUE(goal.Send());
   }
 
@@ -693,13 +755,14 @@
 }
 
 // Tests that the shooter can spin up nicely after being disabled for a while.
-TEST_F(SuperstructureTest, Disabled) {
+TEST_F(SuperstructureTest, ShooterDisabled) {
   {
     auto goal = superstructure_queue_.goal.MakeMessage();
     goal->hood.angle = constants::Values::kHoodRange.lower + 0.03;
     goal->turret.angle = constants::Values::kTurretRange.lower + 0.03;
     goal->intake.distance = constants::Values::kIntakeRange.lower + 0.03;
     goal->shooter.angular_velocity = 200.0;
+    goal->indexer.angular_velocity = 20.0;
     ASSERT_TRUE(goal.Send());
   }
   RunForTime(chrono::seconds(5), false);
@@ -710,6 +773,160 @@
   VerifyNearGoal();
 }
 
+// Tests that when the indexer gets stuck, it detects it and unjams.
+TEST_F(SuperstructureTest, StuckIndexerTest) {
+  // Spin up.
+  {
+    auto goal = superstructure_queue_.goal.MakeMessage();
+    goal->hood.angle = constants::Values::kHoodRange.lower + 0.03;
+    goal->turret.angle = constants::Values::kTurretRange.lower + 0.03;
+    goal->intake.distance = constants::Values::kIntakeRange.lower + 0.03;
+    goal->shooter.angular_velocity = 0.0;
+    goal->indexer.angular_velocity = 5.0;
+    ASSERT_TRUE(goal.Send());
+  }
+
+  RunForTime(chrono::seconds(5));
+  VerifyNearGoal();
+  EXPECT_TRUE(superstructure_queue_.status->indexer.ready);
+
+  // Now, stick it.
+  const auto stuck_start_time = monotonic_clock::now();
+  superstructure_plant_.set_freeze_indexer(true);
+  while (monotonic_clock::now() < stuck_start_time + chrono::seconds(1)) {
+    RunIteration();
+    superstructure_queue_.status.FetchLatest();
+    ASSERT_TRUE(superstructure_queue_.status.get() != nullptr);
+    if (static_cast<indexer::Indexer::State>(
+            superstructure_queue_.status->indexer.state) ==
+        indexer::Indexer::State::REVERSING) {
+      break;
+    }
+  }
+
+  // Make sure it detected it reasonably fast.
+  const auto stuck_detection_time = monotonic_clock::now();
+  EXPECT_TRUE(stuck_detection_time - stuck_start_time <
+              chrono::milliseconds(200));
+
+  // Grab the position we were stuck at.
+  superstructure_queue_.position.FetchLatest();
+  ASSERT_TRUE(superstructure_queue_.position.get() != nullptr);
+  const double indexer_position = superstructure_queue_.position->theta_indexer;
+
+  // Now, unstick it.
+  superstructure_plant_.set_freeze_indexer(false);
+  const auto unstuck_start_time = monotonic_clock::now();
+  while (monotonic_clock::now() < unstuck_start_time + chrono::seconds(1)) {
+    RunIteration();
+    superstructure_queue_.status.FetchLatest();
+    ASSERT_TRUE(superstructure_queue_.status.get() != nullptr);
+    if (static_cast<indexer::Indexer::State>(
+            superstructure_queue_.status->indexer.state) ==
+        indexer::Indexer::State::RUNNING) {
+      break;
+    }
+  }
+
+  // Make sure it took some time, but not too much to detect us not being stuck anymore.
+  const auto unstuck_detection_time = monotonic_clock::now();
+  EXPECT_TRUE(unstuck_detection_time - unstuck_start_time <
+              chrono::milliseconds(200));
+  EXPECT_TRUE(unstuck_detection_time - unstuck_start_time >
+              chrono::milliseconds(40));
+
+  // Verify that it actually moved.
+  superstructure_queue_.position.FetchLatest();
+  ASSERT_TRUE(superstructure_queue_.position.get() != nullptr);
+  const double unstuck_indexer_position =
+      superstructure_queue_.position->theta_indexer;
+  EXPECT_LT(unstuck_indexer_position, indexer_position - 0.1);
+
+  // Now, verify that everything works as expected.
+  RunForTime(chrono::seconds(5));
+  VerifyNearGoal();
+}
+
+// Tests that when the indexer gets stuck forever, it switches back and forth at
+// a reasonable rate.
+TEST_F(SuperstructureTest, ReallyStuckIndexerTest) {
+  // Spin up.
+  {
+    auto goal = superstructure_queue_.goal.MakeMessage();
+    goal->hood.angle = constants::Values::kHoodRange.lower + 0.03;
+    goal->turret.angle = constants::Values::kTurretRange.lower + 0.03;
+    goal->intake.distance = constants::Values::kIntakeRange.lower + 0.03;
+    goal->shooter.angular_velocity = 0.0;
+    goal->indexer.angular_velocity = 5.0;
+    ASSERT_TRUE(goal.Send());
+  }
+
+  RunForTime(chrono::seconds(5));
+  VerifyNearGoal();
+  EXPECT_TRUE(superstructure_queue_.status->indexer.ready);
+
+  // Now, stick it.
+  const auto stuck_start_time = monotonic_clock::now();
+  superstructure_plant_.set_freeze_indexer(true);
+  while (monotonic_clock::now() < stuck_start_time + chrono::seconds(1)) {
+    RunIteration();
+    superstructure_queue_.status.FetchLatest();
+    ASSERT_TRUE(superstructure_queue_.status.get() != nullptr);
+    if (static_cast<indexer::Indexer::State>(
+            superstructure_queue_.status->indexer.state) ==
+        indexer::Indexer::State::REVERSING) {
+      break;
+    }
+  }
+
+  // Make sure it detected it reasonably fast.
+  const auto stuck_detection_time = monotonic_clock::now();
+  EXPECT_TRUE(stuck_detection_time - stuck_start_time <
+              chrono::milliseconds(200));
+
+  // Now, try to unstick it.
+  const auto unstuck_start_time = monotonic_clock::now();
+  while (monotonic_clock::now() < unstuck_start_time + chrono::seconds(1)) {
+    RunIteration();
+    superstructure_queue_.status.FetchLatest();
+    ASSERT_TRUE(superstructure_queue_.status.get() != nullptr);
+    if (static_cast<indexer::Indexer::State>(
+            superstructure_queue_.status->indexer.state) ==
+        indexer::Indexer::State::RUNNING) {
+      break;
+    }
+  }
+
+  // Make sure it took some time, but not too much to detect us not being stuck
+  // anymore.
+  const auto unstuck_detection_time = monotonic_clock::now();
+  EXPECT_TRUE(unstuck_detection_time - unstuck_start_time <
+              chrono::milliseconds(600));
+  EXPECT_TRUE(unstuck_detection_time - unstuck_start_time >
+              chrono::milliseconds(400));
+
+  // Now, make sure it transitions to stuck again after a delay.
+  const auto restuck_start_time = monotonic_clock::now();
+  superstructure_plant_.set_freeze_indexer(true);
+  while (monotonic_clock::now() < restuck_start_time + chrono::seconds(1)) {
+    RunIteration();
+    superstructure_queue_.status.FetchLatest();
+    ASSERT_TRUE(superstructure_queue_.status.get() != nullptr);
+    if (static_cast<indexer::Indexer::State>(
+            superstructure_queue_.status->indexer.state) ==
+        indexer::Indexer::State::REVERSING) {
+      break;
+    }
+  }
+
+  // Make sure it detected it reasonably fast.
+  const auto restuck_detection_time = monotonic_clock::now();
+  EXPECT_TRUE(restuck_detection_time - restuck_start_time >
+              chrono::milliseconds(400));
+  EXPECT_TRUE(restuck_detection_time - restuck_start_time <
+              chrono::milliseconds(600));
+}
+
 }  // namespace testing
 }  // namespace superstructure
 }  // namespace control_loops