SensorReader PWM Refactor.

Refactored the pwm trigger and pwm detecter out of the year specific.

Change-Id: Ie89332fe6e1bcc0f465b742055ec4cf392a20c7e
diff --git a/frc971/wpilib/BUILD b/frc971/wpilib/BUILD
index bc3ac04..910de08 100644
--- a/frc971/wpilib/BUILD
+++ b/frc971/wpilib/BUILD
@@ -276,3 +276,20 @@
         "//aos/logging",
     ],
 )
+
+cc_library(
+    name = "sensor_reader",
+    srcs = [
+        "sensor_reader.cc",
+    ],
+    hdrs = [
+        "sensor_reader.h"
+    ],
+    restricted_to = ["//tools:roborio"],
+    deps = [
+        "//aos:init",
+        "//aos/time:time",
+        "//aos/stl_mutex",
+        "//third_party:wpilib",
+    ],
+)
diff --git a/frc971/wpilib/sensor_reader.cc b/frc971/wpilib/sensor_reader.cc
new file mode 100644
index 0000000..f2123a1
--- /dev/null
+++ b/frc971/wpilib/sensor_reader.cc
@@ -0,0 +1,87 @@
+#include "frc971/wpilib/sensor_reader.h"
+
+#include "aos/init.h"
+#include "aos/util/compiler_memory_barrier.h"
+#include "frc971/wpilib/ahal/DigitalInput.h"
+#include "frc971/wpilib/ahal/Utility.h"
+
+namespace frc971 {
+namespace wpilib {
+
+SensorReader::SensorReader() {}
+
+void SensorReader::set_pwm_trigger(
+    ::std::unique_ptr<frc::DigitalInput> pwm_trigger) {
+  medium_encoder_filter_.Add(pwm_trigger.get());
+  pwm_trigger_ = ::std::move(pwm_trigger);
+}
+
+void SensorReader::RunPWMDetecter() {
+  ::aos::SetCurrentThreadRealtimePriority(41);
+
+  pwm_trigger_->RequestInterrupts();
+  // Rising edge only.
+  pwm_trigger_->SetUpSourceEdge(true, false);
+
+  monotonic_clock::time_point last_posedge_monotonic =
+      monotonic_clock::min_time;
+
+  while (run_) {
+    auto ret = pwm_trigger_->WaitForInterrupt(1.0, true);
+    if (ret == frc::InterruptableSensorBase::WaitResult::kRisingEdge) {
+      // Grab all the clocks.
+      const double pwm_fpga_time = pwm_trigger_->ReadRisingTimestamp();
+
+      aos_compiler_memory_barrier();
+      const double fpga_time_before = frc::GetFPGATime() * 1e-6;
+      aos_compiler_memory_barrier();
+      const monotonic_clock::time_point monotonic_now = monotonic_clock::now();
+      aos_compiler_memory_barrier();
+      const double fpga_time_after = frc::GetFPGATime() * 1e-6;
+      aos_compiler_memory_barrier();
+
+      const double fpga_offset =
+          (fpga_time_after + fpga_time_before) / 2.0 - pwm_fpga_time;
+
+      // Compute when the edge was.
+      const monotonic_clock::time_point monotonic_edge =
+          monotonic_now - chrono::duration_cast<chrono::nanoseconds>(
+                              chrono::duration<double>(fpga_offset));
+
+      LOG(DEBUG, "Got PWM pulse %f spread, %f offset, %lld trigger\n",
+          fpga_time_after - fpga_time_before, fpga_offset,
+          monotonic_edge.time_since_epoch().count());
+
+      // Compute bounds on the timestep and sampling times.
+      const double fpga_sample_length = fpga_time_after - fpga_time_before;
+      const chrono::nanoseconds elapsed_time =
+          monotonic_edge - last_posedge_monotonic;
+
+      last_posedge_monotonic = monotonic_edge;
+
+      // Verify that the values are sane.
+      if (fpga_sample_length > 2e-5 || fpga_sample_length < 0) {
+        continue;
+      }
+      if (fpga_offset < 0 || fpga_offset > 0.00015) {
+        continue;
+      }
+      if (elapsed_time > chrono::microseconds(5050) + chrono::microseconds(4) ||
+          elapsed_time < chrono::microseconds(5050) - chrono::microseconds(4)) {
+        continue;
+      }
+      // Good edge!
+      {
+        ::std::unique_lock<::aos::stl_mutex> locker(tick_time_mutex_);
+        last_tick_time_monotonic_timepoint_ = last_posedge_monotonic;
+        last_period_ = elapsed_time;
+      }
+    } else {
+      LOG(INFO, "PWM triggered %d\n", ret);
+    }
+  }
+  pwm_trigger_->CancelInterrupts();
+}
+
+}  // namespace wpilib
+}  // namespace frc971
diff --git a/frc971/wpilib/sensor_reader.h b/frc971/wpilib/sensor_reader.h
new file mode 100644
index 0000000..23646f1
--- /dev/null
+++ b/frc971/wpilib/sensor_reader.h
@@ -0,0 +1,44 @@
+#ifndef FRC971_WPILIB_SENSOR_READER_H_
+#define FRC971_WPILIB_SENSOR_READER_H_
+
+#include <atomic>
+#include <chrono>
+
+#include "aos/stl_mutex/stl_mutex.h"
+#include "aos/time/time.h"
+#include "frc971/wpilib/ahal/DigitalGlitchFilter.h"
+#include "frc971/wpilib/ahal/DigitalInput.h"
+
+using ::aos::monotonic_clock;
+namespace chrono = ::std::chrono;
+
+namespace frc971 {
+namespace wpilib {
+
+class SensorReader {
+ public:
+  SensorReader();
+
+  void set_pwm_trigger(::std::unique_ptr<frc::DigitalInput> pwm_trigger);
+
+ protected:
+  void RunPWMDetecter();
+
+  ::std::unique_ptr<frc::DigitalInput> pwm_trigger_;
+
+  frc::DigitalGlitchFilter fast_encoder_filter_, medium_encoder_filter_,
+      hall_filter_;
+
+  // Mutex to manage access to the period and tick time variables.
+  ::aos::stl_mutex tick_time_mutex_;
+  monotonic_clock::time_point last_tick_time_monotonic_timepoint_ =
+      monotonic_clock::min_time;
+  chrono::nanoseconds last_period_ = chrono::microseconds(5050);
+
+  ::std::atomic<bool> run_{true};
+};
+
+}  // namespace wpilib
+}  // namespace frc971
+
+#endif  // FRC971_WPILIB_SENSOR_READER_H_