blob: bbd2262f658e2d6fe6b3043014bdd3d023a3ef6f [file] [log] [blame]
Austin Schuh812d0d12021-11-04 20:16:48 -07001// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
Brian Silverman8fce7482020-01-05 13:18:21 -08004
5#include "frc/Timer.h"
6
Austin Schuh812d0d12021-11-04 20:16:48 -07007#include <chrono>
8#include <thread>
9
10#include "frc/DriverStation.h"
11#include "frc/RobotController.h"
Brian Silverman8fce7482020-01-05 13:18:21 -080012
13namespace frc {
14
Austin Schuh812d0d12021-11-04 20:16:48 -070015void Wait(units::second_t seconds) {
16 std::this_thread::sleep_for(std::chrono::duration<double>(seconds.value()));
17}
Brian Silverman8fce7482020-01-05 13:18:21 -080018
Austin Schuh812d0d12021-11-04 20:16:48 -070019units::second_t GetTime() {
20 using std::chrono::duration;
21 using std::chrono::duration_cast;
22 using std::chrono::system_clock;
23
24 return units::second_t(
25 duration_cast<duration<double>>(system_clock::now().time_since_epoch())
26 .count());
27}
Brian Silverman8fce7482020-01-05 13:18:21 -080028
29} // namespace frc
30
31using namespace frc;
32
Austin Schuh812d0d12021-11-04 20:16:48 -070033Timer::Timer() {
34 Reset();
Brian Silverman8fce7482020-01-05 13:18:21 -080035}
36
Austin Schuh812d0d12021-11-04 20:16:48 -070037units::second_t Timer::Get() const {
38 if (m_running) {
39 return (GetFPGATimestamp() - m_startTime) + m_accumulatedTime;
40 } else {
41 return m_accumulatedTime;
42 }
Brian Silverman8fce7482020-01-05 13:18:21 -080043}
44
Austin Schuh812d0d12021-11-04 20:16:48 -070045void Timer::Reset() {
46 m_accumulatedTime = 0_s;
47 m_startTime = GetFPGATimestamp();
48}
49
50void Timer::Start() {
51 if (!m_running) {
52 m_startTime = GetFPGATimestamp();
53 m_running = true;
54 }
55}
56
57void Timer::Stop() {
58 if (m_running) {
59 m_accumulatedTime = Get();
60 m_running = false;
61 }
62}
63
64bool Timer::HasElapsed(units::second_t period) const {
65 return Get() >= period;
66}
67
68bool Timer::HasPeriodPassed(units::second_t period) {
69 return AdvanceIfElapsed(period);
70}
71
72bool Timer::AdvanceIfElapsed(units::second_t period) {
73 if (Get() >= period) {
74 // Advance the start time by the period.
75 m_startTime += period;
76 // Don't set it to the current time... we want to avoid drift.
77 return true;
78 } else {
79 return false;
80 }
81}
82
83units::second_t Timer::GetFPGATimestamp() {
84 // FPGA returns the timestamp in microseconds
85 return units::second_t(frc::RobotController::GetFPGATime() * 1.0e-6);
86}
87
88units::second_t Timer::GetMatchTime() {
89 return units::second_t(frc::DriverStation::GetMatchTime());
Brian Silverman8fce7482020-01-05 13:18:21 -080090}