[wpilibc] Transition C++ classes to units::second_t (#3396)

A lot of these are breaking changes. frc::Timer was replaced with the
contents of frc2::Timer. The others were in-place argument changes or
removing deprecated non-unit overloads.
This commit is contained in:
Tyler Veness
2021-05-28 22:06:59 -07:00
committed by GitHub
parent 827b17a52b
commit e09293a15e
99 changed files with 503 additions and 790 deletions

View File

@@ -7,6 +7,7 @@
#include <memory>
#include <hal/Types.h>
#include <units/time.h>
#include "frc/AnalogTrigger.h"
#include "frc/CounterBase.h"
@@ -368,7 +369,7 @@ class Counter : public CounterBase,
*
* @returns The period between the last two pulses in units of seconds.
*/
double GetPeriod() const override;
units::second_t GetPeriod() const override;
/**
* Set the maximum period where the device is still considered "moving".
@@ -380,7 +381,7 @@ class Counter : public CounterBase,
* @param maxPeriod The maximum period where the counted device is considered
* moving in seconds.
*/
void SetMaxPeriod(double maxPeriod) final;
void SetMaxPeriod(units::second_t maxPeriod) final;
/**
* Select whether you want to continue updating the event timer output when

View File

@@ -4,6 +4,8 @@
#pragma once
#include <units/time.h>
namespace frc {
/**
@@ -27,8 +29,8 @@ class CounterBase {
virtual int Get() const = 0;
virtual void Reset() = 0;
virtual double GetPeriod() const = 0;
virtual void SetMaxPeriod(double maxPeriod) = 0;
virtual units::second_t GetPeriod() const = 0;
virtual void SetMaxPeriod(units::second_t maxPeriod) = 0;
virtual bool GetStopped() const = 0;
virtual bool GetDirection() const = 0;
};

View File

@@ -12,6 +12,7 @@
#include <fmt/format.h>
#include <hal/DriverStationTypes.h>
#include <units/time.h>
#include <wpi/condition_variable.h>
#include <wpi/mutex.h>
@@ -334,11 +335,11 @@ class DriverStation {
* This is a good way to delay processing until there is new driver station
* data to act on.
*
* @param timeout Timeout time in seconds
* @param timeout Timeout
*
* @return true if new data, otherwise false
*/
bool WaitForData(double timeout);
bool WaitForData(units::second_t timeout);
/**
* Return the approximate match time.
@@ -494,7 +495,7 @@ class DriverStation {
bool m_userInTeleop = false;
bool m_userInTest = false;
double m_nextMessageTime = 0;
units::second_t m_nextMessageTime = 0_s;
};
} // namespace frc

View File

@@ -167,7 +167,7 @@ class Encoder : public CounterBase,
*
* @return Period in seconds of the most recent pulse.
*/
double GetPeriod() const override;
units::second_t GetPeriod() const override;
/**
* Sets the maximum period for stopped detection.
@@ -188,7 +188,7 @@ class Encoder : public CounterBase,
WPI_DEPRECATED(
"Use SetMinRate() in favor of this method. This takes unscaled periods "
"and SetMinRate() scales using value from SetDistancePerPulse().")
void SetMaxPeriod(double maxPeriod) override;
void SetMaxPeriod(units::second_t maxPeriod) override;
/**
* Determine if the encoder is stopped.

View File

@@ -8,6 +8,7 @@
#include <memory>
#include <hal/Interrupts.h>
#include <units/time.h>
#include "frc/AnalogTriggerType.h"
@@ -86,12 +87,12 @@ class InterruptableSensorBase {
* waiting for an interrupt. This is not threadsafe, and can cause memory
* corruption
*
* @param timeout Timeout in seconds
* @param timeout Timeout
* @param ignorePrevious If true, ignore interrupts that happened before
* WaitForInterrupt was called.
* @return What interrupts fired
*/
virtual WaitResult WaitForInterrupt(double timeout,
virtual WaitResult WaitForInterrupt(units::second_t timeout,
bool ignorePrevious = true);
/**
@@ -116,7 +117,7 @@ class InterruptableSensorBase {
*
* @return Timestamp in seconds since boot.
*/
virtual double ReadRisingTimestamp();
virtual units::second_t ReadRisingTimestamp();
/**
* Return the timestamp for the falling interrupt that occurred most recently.
@@ -127,7 +128,7 @@ class InterruptableSensorBase {
*
* @return Timestamp in seconds since boot.
*/
virtual double ReadFallingTimestamp();
virtual units::second_t ReadFallingTimestamp();
/**
* Set which edge to trigger interrupts on

View File

@@ -6,6 +6,7 @@
#include <string>
#include <units/time.h>
#include <wpi/mutex.h>
#include "frc/Timer.h"
@@ -36,16 +37,16 @@ class MotorSafety {
/**
* Set the expiration time for the corresponding motor safety object.
*
* @param expirationTime The timeout value in seconds.
* @param expirationTime The timeout value.
*/
void SetExpiration(double expirationTime);
void SetExpiration(units::second_t expirationTime);
/**
* Retrieve the timeout value for the corresponding motor safety object.
*
* @return the timeout value in seconds.
* @return the timeout value.
*/
double GetExpiration() const;
units::second_t GetExpiration() const;
/**
* Determine if the motor is still operating or has timed out.
@@ -93,16 +94,16 @@ class MotorSafety {
virtual std::string GetDescription() const = 0;
private:
static constexpr double kDefaultSafetyExpiration = 0.1;
static constexpr auto kDefaultSafetyExpiration = 100_ms;
// The expiration time for this object
double m_expiration = kDefaultSafetyExpiration;
units::second_t m_expiration = kDefaultSafetyExpiration;
// True if motor safety is enabled for this motor
bool m_enabled = false;
// The FPGA clock value when the motor has expired
double m_stopTime = Timer::GetFPGATimestamp();
units::second_t m_stopTime = Timer::GetFPGATimestamp();
mutable wpi::mutex m_thisMutex;
};

View File

@@ -15,7 +15,6 @@
#include <hal/Types.h>
#include <units/time.h>
#include <wpi/deprecated.h>
#include <wpi/mutex.h>
namespace frc {
@@ -80,19 +79,6 @@ class Notifier {
*/
void SetHandler(std::function<void()> handler);
/**
* Register for single event notification.
*
* A timer event is queued for a single event after the specified delay.
*
* @deprecated Use unit-safe StartSingle(units::second_t delay) method
* instead.
*
* @param delay Seconds to wait before the handler is called.
*/
WPI_DEPRECATED("Use unit-safe StartSingle method instead.")
void StartSingle(double delay);
/**
* Register for single event notification.
*
@@ -102,22 +88,6 @@ class Notifier {
*/
void StartSingle(units::second_t delay);
/**
* Register for periodic event notification.
*
* A timer event is queued for periodic event notification. Each time the
* interrupt occurs, the event will be immediately requeued for the same time
* interval.
*
* @deprecated Use unit-safe StartPeriodic(units::second_t period) method
* instead
*
* @param period Period in seconds to call the handler starting one period
* after the call to this method.
*/
WPI_DEPRECATED("Use unit-safe StartPeriodic method instead.")
void StartPeriodic(double period);
/**
* Register for periodic event notification.
*
@@ -184,10 +154,10 @@ class Notifier {
std::function<void()> m_handler;
// The absolute expiration time
double m_expirationTime = 0;
units::second_t m_expirationTime = 0_s;
// The relative time (either periodic or single)
double m_period = 0;
units::second_t m_period = 0_s;
// True if this is a periodic event
bool m_periodic = false;

View File

@@ -242,32 +242,6 @@ class SPI {
int ReadAutoReceivedData(uint32_t* buffer, int numToRead,
units::second_t timeout);
/**
* Read data that has been transferred by the automatic SPI transfer engine.
*
* Transfers may be made a byte at a time, so it's necessary for the caller
* to handle cases where an entire transfer has not been completed.
*
* Each received data sequence consists of a timestamp followed by the
* received data bytes, one byte per word (in the least significant byte).
* The length of each received data sequence is the same as the combined
* size of the data and zeroSize set in SetAutoTransmitData().
*
* Blocks until numToRead words have been read or timeout expires.
* May be called with numToRead=0 to retrieve how many words are available.
*
* @deprecated Use unit safe version instead.
* ReadAutoReceivedData(uint32_t* buffer, int numToRead, <!--
* --> units::second_t timeout)
*
* @param buffer buffer where read words are stored
* @param numToRead number of words to read
* @param timeout timeout in seconds (ms resolution)
* @return Number of words remaining to be read
*/
WPI_DEPRECATED("Use ReadAutoReceivedData with unit-safety instead")
int ReadAutoReceivedData(uint32_t* buffer, int numToRead, double timeout);
/**
* Get the number of bytes dropped by the automatic SPI transfer engine due
* to the receive buffer being full.

View File

@@ -8,7 +8,7 @@
#include <string_view>
#include <hal/Types.h>
#include <wpi/deprecated.h>
#include <units/time.h>
namespace frc {
@@ -155,9 +155,9 @@ class SerialPort {
* This defines the timeout for transactions with the hardware.
* It will affect reads and very large writes.
*
* @param timeout The number of seconds to to wait for I/O.
* @param timeout The time to wait for I/O.
*/
void SetTimeout(double timeout);
void SetTimeout(units::second_t timeout);
/**
* Specify the size of the input buffer.

View File

@@ -4,12 +4,12 @@
#pragma once
#include <frc2/Timer.h>
#include <algorithm>
#include <units/time.h>
#include "frc/Timer.h"
namespace frc {
/**
* A class that limits the rate of change of an input value. Useful for
@@ -36,7 +36,7 @@ class SlewRateLimiter {
explicit SlewRateLimiter(Rate_t rateLimit, Unit_t initialValue = Unit_t{0})
: m_rateLimit{rateLimit},
m_prevVal{initialValue},
m_prevTime{frc2::Timer::GetFPGATimestamp()} {}
m_prevTime{Timer::GetFPGATimestamp()} {}
/**
* Filters the input to limit its slew rate.
@@ -46,7 +46,7 @@ class SlewRateLimiter {
* rate.
*/
Unit_t Calculate(Unit_t input) {
units::second_t currentTime = frc2::Timer::GetFPGATimestamp();
units::second_t currentTime = Timer::GetFPGATimestamp();
units::second_t elapsedTime = currentTime - m_prevTime;
m_prevVal += std::clamp(input - m_prevVal, -m_rateLimit * elapsedTime,
m_rateLimit * elapsedTime);
@@ -62,7 +62,7 @@ class SlewRateLimiter {
*/
void Reset(Unit_t value) {
m_prevVal = value;
m_prevTime = frc2::Timer::GetFPGATimestamp();
m_prevTime = Timer::GetFPGATimestamp();
}
private:

View File

@@ -5,6 +5,7 @@
#pragma once
#include <hal/Types.h>
#include <units/time.h>
#include "frc/SolenoidBase.h"
#include "frc/smartdashboard/Sendable.h"
@@ -93,7 +94,7 @@ class Solenoid : public SolenoidBase,
*
* @see startPulse()
*/
void SetPulseDuration(double durationSeconds);
void SetPulseDuration(units::second_t duration);
/**
* Trigger the PCM to generate a pulse of the duration set in

View File

@@ -15,7 +15,7 @@
#include <wpi/priority_queue.h>
#include "frc/IterativeRobotBase.h"
#include "frc2/Timer.h"
#include "frc/Timer.h"
namespace frc {
@@ -30,7 +30,7 @@ namespace frc {
*/
class TimedRobot : public IterativeRobotBase {
public:
static constexpr units::second_t kDefaultPeriod = 20_ms;
static constexpr auto kDefaultPeriod = 20_ms;
/**
* Provide an alternate "main loop" via StartCompetition().
@@ -99,12 +99,11 @@ class TimedRobot : public IterativeRobotBase {
units::second_t period, units::second_t offset)
: func{std::move(func)},
period{period},
expirationTime{
startTime + offset +
units::math::floor((frc2::Timer::GetFPGATimestamp() - startTime) /
period) *
period +
period} {}
expirationTime{startTime + offset +
units::math::floor(
(Timer::GetFPGATimestamp() - startTime) / period) *
period +
period} {}
bool operator>(const Callback& rhs) const {
return expirationTime > rhs.expirationTime;

View File

@@ -4,7 +4,7 @@
#pragma once
#include "frc2/Timer.h"
#include <units/time.h>
namespace frc {
@@ -18,23 +18,17 @@ namespace frc {
*
* @param seconds Length of time to pause, in seconds.
*/
void Wait(double seconds);
void Wait(units::second_t seconds);
/**
* @brief Gives real-time clock system time with nanosecond resolution
* @return The time, just in case you want the robot to start autonomous at 8pm
* on Saturday.
*/
double GetTime();
units::second_t GetTime();
/**
* Timer objects measure accumulated time in seconds.
*
* The timer object functions like a stopwatch. It can be started, stopped, and
* cleared. When the timer is running its value counts up in seconds. When
* stopped, the timer holds the current value. The implementation simply records
* the time when started and subtracts the current time whenever the value is
* requested.
* A wrapper for the frc::Timer class that returns unit-typed values.
*/
class Timer {
public:
@@ -48,10 +42,10 @@ class Timer {
virtual ~Timer() = default;
Timer(const Timer& rhs) = default;
Timer& operator=(const Timer& rhs) = default;
Timer(Timer&& rhs) = default;
Timer& operator=(Timer&& rhs) = default;
Timer(const Timer&) = default;
Timer& operator=(const Timer&) = default;
Timer(Timer&&) = default;
Timer& operator=(Timer&&) = default;
/**
* Get the current time from the timer. If the clock is running it is derived
@@ -60,7 +54,7 @@ class Timer {
*
* @return Current time value for this timer in seconds
*/
double Get() const;
units::second_t Get() const;
/**
* Reset the timer by setting the time to 0.
@@ -74,7 +68,8 @@ class Timer {
* Start the timer running.
*
* Just set the running flag to true indicating that all time requests should
* be relative to the system clock.
* be relative to the system clock. Note that this method is a no-op if the
* timer is already running.
*/
void Start();
@@ -87,15 +82,33 @@ class Timer {
*/
void Stop();
/**
* Check if the period specified has passed.
*
* @param seconds The period to check.
* @return True if the period has passed.
*/
bool HasElapsed(units::second_t period) const;
/**
* Check if the period specified has passed and if it has, advance the start
* time by that period. This is useful to decide if it's time to do periodic
* work without drifting later by the time it took to get around to checking.
*
* @param period The period to check for (in seconds).
* @param period The period to check for.
* @return True if the period has passed.
*/
bool HasPeriodPassed(double period);
bool HasPeriodPassed(units::second_t period);
/**
* Check if the period specified has passed and if it has, advance the start
* time by that period. This is useful to decide if it's time to do periodic
* work without drifting later by the time it took to get around to checking.
*
* @param period The period to check for.
* @return True if the period has passed.
*/
bool AdvanceIfElapsed(units::second_t period);
/**
* Return the FPGA system clock time in seconds.
@@ -105,7 +118,7 @@ class Timer {
*
* @returns Robot running time in seconds.
*/
static double GetFPGATimestamp();
static units::second_t GetFPGATimestamp();
/**
* Return the approximate match time.
@@ -122,10 +135,12 @@ class Timer {
*
* @return Time remaining in current match period (auto or teleop)
*/
static double GetMatchTime();
static units::second_t GetMatchTime();
private:
frc2::Timer m_timer;
units::second_t m_startTime = 0_s;
units::second_t m_accumulatedTime = 0_s;
bool m_running = false;
};
} // namespace frc

View File

@@ -10,6 +10,8 @@
#include <vector>
#include <hal/SimDevice.h>
#include <units/time.h>
#include <units/velocity.h>
#include "frc/Counter.h"
#include "frc/smartdashboard/Sendable.h"
@@ -174,8 +176,8 @@ class Ultrasonic : public Sendable, public SendableHelper<Ultrasonic> {
static constexpr int kPriority = 64;
// Max time (ms) between readings.
static constexpr double kMaxUltrasonicTime = 0.1;
static constexpr double kSpeedOfSoundInchesPerSec = 1130.0 * 12.0;
static constexpr auto kMaxUltrasonicTime = 0.1_s;
static constexpr auto kSpeedOfSound = 1130_fps;
// Thread doing the round-robin automatic sensing
static std::thread m_thread;

View File

@@ -9,7 +9,6 @@
#include <units/time.h>
#include <wpi/StringRef.h>
#include <wpi/deprecated.h>
#include "frc/Tracer.h"
@@ -26,19 +25,6 @@ namespace frc {
*/
class Watchdog {
public:
/**
* Watchdog constructor.
*
* @deprecated use unit-safe version instead.
* Watchdog(units::second_t timeout, std::function<void()> callback)
*
* @param timeout The watchdog's timeout in seconds with microsecond
* resolution.
* @param callback This function is called when the timeout expires.
*/
WPI_DEPRECATED("Use unit-safe version instead")
Watchdog(double timeout, std::function<void()> callback);
/**
* Watchdog constructor.
*
@@ -48,11 +34,6 @@ class Watchdog {
*/
Watchdog(units::second_t timeout, std::function<void()> callback);
template <typename Callable, typename Arg, typename... Args>
WPI_DEPRECATED("Use unit-safe version instead")
Watchdog(double timeout, Callable&& f, Arg&& arg, Args&&... args)
: Watchdog(units::second_t{timeout}, arg, args...) {}
template <typename Callable, typename Arg, typename... Args>
Watchdog(units::second_t timeout, Callable&& f, Arg&& arg, Args&&... args)
: Watchdog(timeout,
@@ -65,21 +46,9 @@ class Watchdog {
Watchdog& operator=(Watchdog&& rhs);
/**
* Returns the time in seconds since the watchdog was last fed.
* Returns the time since the watchdog was last fed.
*/
double GetTime() const;
/**
* Sets the watchdog's timeout.
*
* @deprecated use the unit safe version instead.
* SetTimeout(units::second_t timeout)
*
* @param timeout The watchdog's timeout in seconds with microsecond
* resolution.
*/
WPI_DEPRECATED("Use unit-safe version instead")
void SetTimeout(double timeout);
units::second_t GetTime() const;
/**
* Sets the watchdog's timeout.
@@ -90,9 +59,9 @@ class Watchdog {
void SetTimeout(units::second_t timeout);
/**
* Returns the watchdog's timeout in seconds.
* Returns the watchdog's timeout.
*/
double GetTimeout() const;
units::second_t GetTimeout() const;
/**
* Returns true if the watchdog timer has expired.
@@ -143,7 +112,7 @@ class Watchdog {
private:
// Used for timeout print rate-limiting
static constexpr units::second_t kMinPrintPeriod = 1_s;
static constexpr auto kMinPrintPeriod = 1_s;
units::second_t m_startTime = 0_s;
units::second_t m_timeout;

View File

@@ -1,148 +0,0 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <units/time.h>
#include <wpi/mutex.h>
namespace frc2 {
/**
* Pause the task for a specified time.
*
* Pause the execution of the program for a specified period of time given in
* seconds. Motors will continue to run at their last assigned values, and
* sensors will continue to update. Only the task containing the wait will pause
* until the wait time is expired.
*
* @param seconds Length of time to pause, in seconds.
*/
void Wait(units::second_t seconds);
/**
* @brief Gives real-time clock system time with nanosecond resolution
* @return The time, just in case you want the robot to start autonomous at 8pm
* on Saturday.
*/
units::second_t GetTime();
/**
* A wrapper for the frc::Timer class that returns unit-typed values.
*/
class Timer {
public:
/**
* Create a new timer object.
*
* Create a new timer object and reset the time to zero. The timer is
* initially not running and must be started.
*/
Timer();
virtual ~Timer() = default;
Timer(const Timer& rhs);
Timer& operator=(const Timer& rhs);
Timer(Timer&& rhs);
Timer& operator=(Timer&& rhs);
/**
* Get the current time from the timer. If the clock is running it is derived
* from the current system clock the start time stored in the timer class. If
* the clock is not running, then return the time when it was last stopped.
*
* @return Current time value for this timer in seconds
*/
units::second_t Get() const;
/**
* Reset the timer by setting the time to 0.
*
* Make the timer startTime the current time so new requests will be relative
* to now.
*/
void Reset();
/**
* Start the timer running.
*
* Just set the running flag to true indicating that all time requests should
* be relative to the system clock. Note that this method is a no-op if the
* timer is already running.
*/
void Start();
/**
* Stop the timer.
*
* This computes the time as of now and clears the running flag, causing all
* subsequent time requests to be read from the accumulated time rather than
* looking at the system clock.
*/
void Stop();
/**
* Check if the period specified has passed.
*
* @param seconds The period to check.
* @return True if the period has passed.
*/
bool HasElapsed(units::second_t period) const;
/**
* Check if the period specified has passed and if it has, advance the start
* time by that period. This is useful to decide if it's time to do periodic
* work without drifting later by the time it took to get around to checking.
*
* @param period The period to check for.
* @return True if the period has passed.
*/
bool HasPeriodPassed(units::second_t period);
/**
* Check if the period specified has passed and if it has, advance the start
* time by that period. This is useful to decide if it's time to do periodic
* work without drifting later by the time it took to get around to checking.
*
* @param period The period to check for.
* @return True if the period has passed.
*/
bool AdvanceIfElapsed(units::second_t period);
/**
* Return the FPGA system clock time in seconds.
*
* Return the time from the FPGA hardware clock in seconds since the FPGA
* started. Rolls over after 71 minutes.
*
* @returns Robot running time in seconds.
*/
static units::second_t GetFPGATimestamp();
/**
* Return the approximate match time.
*
* The FMS does not send an official match time to the robots, but does send
* an approximate match time. The value will count down the time remaining in
* the current period (auto or teleop).
*
* Warning: This is not an official time (so it cannot be used to dispute ref
* calls or guarantee that a function will trigger before the match ends).
*
* The Practice Match function of the DS approximates the behavior seen on the
* field.
*
* @return Time remaining in current match period (auto or teleop)
*/
static units::second_t GetMatchTime();
private:
units::second_t m_startTime = 0_s;
units::second_t m_accumulatedTime = 0_s;
bool m_running = false;
mutable wpi::mutex m_mutex;
};
} // namespace frc2