Brian Silverman | 7be68ba | 2020-01-08 22:08:40 -0800 | [diff] [blame] | 1 | #include "frc971/wpilib/fpga_time_conversion.h" |
| 2 | |
| 3 | #include "aos/util/compiler_memory_barrier.h" |
| 4 | |
| 5 | namespace frc971 { |
| 6 | namespace wpilib { |
| 7 | |
| 8 | std::optional<std::chrono::nanoseconds> CalculateFpgaOffset() { |
| 9 | aos_compiler_memory_barrier(); |
| 10 | const hal::fpga_clock::time_point fpga_time_before = hal::fpga_clock::now(); |
| 11 | aos_compiler_memory_barrier(); |
| 12 | const aos::monotonic_clock::time_point monotonic_now = |
| 13 | aos::monotonic_clock::now(); |
| 14 | aos_compiler_memory_barrier(); |
| 15 | const hal::fpga_clock::time_point fpga_time_after = hal::fpga_clock::now(); |
| 16 | aos_compiler_memory_barrier(); |
| 17 | |
| 18 | const std::chrono::nanoseconds fpga_sample_length = |
| 19 | fpga_time_after - fpga_time_before; |
| 20 | |
| 21 | if (fpga_sample_length < fpga_sample_length.zero()) { |
| 22 | return std::nullopt; |
| 23 | } |
| 24 | if (fpga_sample_length > std::chrono::microseconds(20)) { |
| 25 | return std::nullopt; |
| 26 | } |
| 27 | |
| 28 | const std::chrono::nanoseconds fpga_average = |
| 29 | (fpga_time_after.time_since_epoch() + |
| 30 | fpga_time_before.time_since_epoch()) / |
| 31 | 2; |
| 32 | return monotonic_now.time_since_epoch() - fpga_average; |
| 33 | } |
| 34 | |
| 35 | } // namespace wpilib |
| 36 | } // namespace frc971 |