From 443401e4a32d96b8a7050061622d999d79974e0d Mon Sep 17 00:00:00 2001 From: Jun Jie Huang <1juhuang2@duck.com> Date: Sun, 15 Nov 2026 20:50:07 -0800 Subject: [PATCH] Replace XTimer with WPILib Timer and SimHooks Remove the XTimer facade, its implementations, and the Dagger timer bindings. Library code reads Timer.getMonotonicTimestamp() directly, and tests control time through WPILib's simulated clock: BaseWPITest pauses it and tests advance it with SimHooks.stepTiming(). Co-Authored-By: Claude --- AGENTS.md | 7 ++- .../java/xbot/common/command/BaseRobot.java | 8 +-- .../common/command/BaseSetpointSubsystem.java | 8 +-- .../command/BaseWaitForMaintainerCommand.java | 6 +- .../command/DelayViaSupplierCommand.java | 6 +- .../SimpleWaitForMaintainerCommand.java | 6 +- .../controls/sensors/XSettableTimerImpl.java | 21 ------- .../xbot/common/controls/sensors/XTimer.java | 40 ------------- .../common/controls/sensors/XTimerImpl.java | 9 --- .../sensors/mock_adapters/MockLaserCAN.java | 7 ++- .../sensors/mock_adapters/MockTimer.java | 47 ---------------- .../wpi_adapters/LaserCANWpiAdapter.java | 11 ++-- .../wpi_adapters/LidarLiteWpiAdapter.java | 6 +- .../sensors/wpi_adapters/TimerWpiAdapter.java | 41 -------------- .../xbot/common/injection/BaseWPITest.java | 12 ++-- .../injection/components/BaseComponent.java | 6 -- .../common/injection/modules/RobotModule.java | 11 ---- .../injection/modules/SimulationModule.java | 11 ---- .../injection/modules/UnitTestModule.java | 11 ---- .../java/xbot/common/logging/TimeLogger.java | 4 +- .../xbot/common/logic/CalibrationDecider.java | 6 +- .../xbot/common/logic/FiniteStateMachine.java | 12 ++-- .../java/xbot/common/logic/FsmContext.java | 2 +- .../common/logic/HumanVsMachineDecider.java | 6 +- .../common/logic/HumanVsMachineState.java | 7 +-- .../common/logic/ReadMeFiniteStateMachine.md | 6 +- .../java/xbot/common/logic/StallDetector.java | 6 +- .../common/logic/TimeStableValidator.java | 7 ++- .../java/xbot/common/logic/WatchdogTimer.java | 7 ++- .../math/InterpolatingFieldPoseBuffer.java | 9 ++- .../math/InterpolatingHistoryBuffer.java | 4 +- src/main/java/xbot/common/math/PID.java | 6 +- .../drive/BaseSwerveDriveSubsystem.java | 4 +- .../control_logic/HeadingAssistModule.java | 6 +- .../subsystems/feedback/RumbleManager.java | 6 +- .../subsystems/pose/BasePoseSubsystem.java | 10 ++-- .../trajectory/SimpleTimeInterpolator.java | 6 +- .../BaseWaitForMaintainerCommandTest.java | 4 +- .../RealTunableCommandPublisherTest.java | 3 - .../SimpleWaitForMaintainerCommandTest.java | 6 +- .../xbot/common/injection/MockTimerTest.java | 56 ------------------- .../xbot/common/logging/TimeLoggerTest.java | 10 ++-- .../common/logic/CalibrationDeciderTest.java | 12 ++-- .../FiniteStateMachineReadMeExampleTest.java | 31 +++++----- .../common/logic/FiniteStateMachineTest.java | 16 +++--- .../logic/HumanVsMachineDeciderTest.java | 15 ++--- .../xbot/common/logic/StallDetectorTest.java | 36 ++++++------ .../common/logic/TimeStableValidatorTest.java | 16 +++--- .../xbot/common/logic/WatchdogTimerTest.java | 26 +++++---- .../xbot/common/math/HistoryBufferTests.java | 29 ++++++---- .../java/xbot/common/math/PIDManagerTest.java | 13 ++--- .../drive/HeadingAssistModuleTest.java | 6 +- .../subsystems/drive/HeadingModuleTest.java | 4 +- .../drive/PurePursuitCommandTest.java | 3 +- .../feedback/RumbleManagerTest.java | 7 +-- .../common/subsystems/pose/BasePoseTest.java | 6 +- .../commands/SetRobotHeadingCommandTest.java | 6 +- .../SimpleTimeInterpolatorTest.java | 23 ++++---- 58 files changed, 241 insertions(+), 475 deletions(-) delete mode 100644 src/main/java/xbot/common/controls/sensors/XSettableTimerImpl.java delete mode 100644 src/main/java/xbot/common/controls/sensors/XTimer.java delete mode 100644 src/main/java/xbot/common/controls/sensors/XTimerImpl.java delete mode 100644 src/main/java/xbot/common/controls/sensors/mock_adapters/MockTimer.java delete mode 100644 src/main/java/xbot/common/controls/sensors/wpi_adapters/TimerWpiAdapter.java delete mode 100644 src/test/java/xbot/common/injection/MockTimerTest.java diff --git a/AGENTS.md b/AGENTS.md index 944be8c41..f2aece307 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,7 +86,7 @@ All commands use the Gradle wrapper from the repository root. |---|---|---| | Custom library classes | `X` prefix | `XGyro`, `XEncoder`, `XCANMotorController` | | Base/abstract classes | `Base` prefix | `BaseCommand`, `BaseSubsystem`, `BaseRobot` | -| Mock/test implementations | `Mock` prefix | `MockGyro`, `MockTimer` | +| Mock/test implementations | `Mock` prefix | `MockGyro`, `MockLaserCAN` | | WPILib adapter classes | `*WpiAdapter` suffix | `PowerDistributionPanelWPIAdapter` | | Interfaces | `I` prefix (optional) | `ITableProxy` | | Packages | all lowercase, dots allowed | `xbot.common.math` | @@ -170,8 +170,9 @@ through the abstract base class and inject the concrete implementation via Dagge - All tests extend `BaseWPITest` (located in `xbot.common.injection`) and implement `createDaggerComponent()` to provide a Dagger component wired with mock modules. - Tests are plain JUnit 4 (`@Test`, `@Before`, `@After`). -- The `MockTimer` (injected as `timer` in `BaseWPITest`) controls simulated time; advance it - manually where time-dependent logic is tested. +- `BaseWPITest` pauses WPILib's simulated clock; advance it with `SimHooks.stepTiming(seconds)` where + time-dependent logic is tested. The clock does not start at zero, so measure time relative to a + timestamp captured in the test. - Test classes live in `src/test/java/` mirroring the package of the class under test. - Aim for unit tests that do not require hardware, network, or file I/O. diff --git a/src/main/java/xbot/common/command/BaseRobot.java b/src/main/java/xbot/common/command/BaseRobot.java index c680b7a4d..45fa87eca 100644 --- a/src/main/java/xbot/common/command/BaseRobot.java +++ b/src/main/java/xbot/common/command/BaseRobot.java @@ -17,11 +17,10 @@ import org.wpilib.hardware.bus.CANPort; import org.wpilib.hardware.power.PowerDistribution; import org.wpilib.system.RobotController; +import org.wpilib.system.Timer; import org.wpilib.tunable.Tunables; import xbot.common.advantage.TunableSkippingNT4Publisher; -import xbot.common.controls.sensors.XTimer; -import xbot.common.controls.sensors.XTimerImpl; import xbot.common.injection.DevicePolice; import xbot.common.injection.components.BaseComponent; import xbot.common.logging.assertion.RobotAssertionManager; @@ -172,9 +171,6 @@ protected void updateLoggingContext() { protected void initializeSystems() { updateLoggingContext(); // override with additional systems (but call this one too) - XTimerImpl timerimpl = injectorComponent.timerImplementation(); - XTimer.setImplementation(timerimpl); - tunableManager = injectorComponent.tunableManager(); xScheduler = injectorComponent.scheduler(); xScheduler.reset(); @@ -280,6 +276,6 @@ public void refreshAllDataFrames() { } protected double getPerformanceTimestampInMs() { - return XTimer.getFPGATimestamp() * 1000.0; + return Timer.getMonotonicTimestamp() * 1000.0; } } diff --git a/src/main/java/xbot/common/command/BaseSetpointSubsystem.java b/src/main/java/xbot/common/command/BaseSetpointSubsystem.java index 5191237bc..3bdbb66e9 100644 --- a/src/main/java/xbot/common/command/BaseSetpointSubsystem.java +++ b/src/main/java/xbot/common/command/BaseSetpointSubsystem.java @@ -1,8 +1,7 @@ package xbot.common.command; import org.wpilib.command2.Subsystem; - -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; /** * Base class for subsystems that have a setpoint managed by a maintainer. @@ -42,7 +41,7 @@ public boolean isMaintainerAtGoal() { return false; } - if (XTimer.getFPGATimestamp() - lastUpdateTimeFromMaintainer > 0.5) { + if (Timer.getMonotonicTimestamp() - lastUpdateTimeFromMaintainer > 0.5) { // If we haven't heard from the maintainer within the last 0.5 seconds, // then assume the system is not ready. return false; @@ -52,8 +51,9 @@ public boolean isMaintainerAtGoal() { } public void setMaintainerIsAtGoal(boolean atGoal) { - lastUpdateTimeFromMaintainer = XTimer.getFPGATimestamp(); + lastUpdateTimeFromMaintainer = Timer.getMonotonicTimestamp(); this.atGoal = atGoal; + lastTargetValueUsedforAtGoal = getTargetValue(); } diff --git a/src/main/java/xbot/common/command/BaseWaitForMaintainerCommand.java b/src/main/java/xbot/common/command/BaseWaitForMaintainerCommand.java index de9bc5e41..752bb1d27 100644 --- a/src/main/java/xbot/common/command/BaseWaitForMaintainerCommand.java +++ b/src/main/java/xbot/common/command/BaseWaitForMaintainerCommand.java @@ -1,8 +1,8 @@ package xbot.common.command; +import org.wpilib.system.Timer; import org.wpilib.tunable.TunableDouble; -import xbot.common.controls.sensors.XTimer; import xbot.common.properties.TunableFactory; /** @@ -24,7 +24,7 @@ public BaseWaitForMaintainerCommand(BaseSetpointSubsystem system, TunableF @Override public void initialize() { - this.startTime = XTimer.getFPGATimestamp(); + this.startTime = Timer.getMonotonicTimestamp(); } @Override @@ -38,6 +38,6 @@ public boolean isFinished() { } private boolean isTimeoutExpired() { - return XTimer.getFPGATimestamp() > this.startTime + this.timeoutTunable.get(); + return Timer.getMonotonicTimestamp() > this.startTime + this.timeoutTunable.get(); } } diff --git a/src/main/java/xbot/common/command/DelayViaSupplierCommand.java b/src/main/java/xbot/common/command/DelayViaSupplierCommand.java index 0a3210f08..74b679822 100644 --- a/src/main/java/xbot/common/command/DelayViaSupplierCommand.java +++ b/src/main/java/xbot/common/command/DelayViaSupplierCommand.java @@ -2,7 +2,7 @@ import java.util.function.DoubleSupplier; -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; public class DelayViaSupplierCommand extends BaseCommand { @@ -15,7 +15,7 @@ public DelayViaSupplierCommand(DoubleSupplier delaySupplier) { @Override public void initialize() { - this.startTime = XTimer.getFPGATimestamp(); + this.startTime = Timer.getMonotonicTimestamp(); log.info("Initializing with intial time: " + startTime + " and waiting for " + delaySupplier.getAsDouble() + " seconds"); } @@ -30,6 +30,6 @@ public boolean isFinished() { } private boolean isTimeoutExpired() { - return XTimer.getFPGATimestamp() > startTime + delaySupplier.getAsDouble(); + return Timer.getMonotonicTimestamp() > startTime + delaySupplier.getAsDouble(); } } diff --git a/src/main/java/xbot/common/command/SimpleWaitForMaintainerCommand.java b/src/main/java/xbot/common/command/SimpleWaitForMaintainerCommand.java index 71589f21f..fce93c13c 100644 --- a/src/main/java/xbot/common/command/SimpleWaitForMaintainerCommand.java +++ b/src/main/java/xbot/common/command/SimpleWaitForMaintainerCommand.java @@ -2,7 +2,7 @@ import java.util.function.DoubleSupplier; -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; /** * Command that waits for a maintainer to be at its goal or until a timeout. @@ -28,7 +28,7 @@ public SimpleWaitForMaintainerCommand(BaseSetpointSubsystem subsystem, Dou @Override public void initialize() { - this.startTime = XTimer.getFPGATimestamp(); + this.startTime = Timer.getMonotonicTimestamp(); } @Override @@ -42,6 +42,6 @@ public boolean isFinished() { } private boolean isTimeoutExpired() { - return XTimer.getFPGATimestamp() > startTime + delaySupplier.getAsDouble(); + return Timer.getMonotonicTimestamp() > startTime + delaySupplier.getAsDouble(); } } diff --git a/src/main/java/xbot/common/controls/sensors/XSettableTimerImpl.java b/src/main/java/xbot/common/controls/sensors/XSettableTimerImpl.java deleted file mode 100644 index 3bce578b3..000000000 --- a/src/main/java/xbot/common/controls/sensors/XSettableTimerImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -package xbot.common.controls.sensors; - -public interface XSettableTimerImpl extends XTimerImpl { - - /** - * Set the current time - * - * @param time - * The current time in seconds - */ - public void setTimeInSeconds(double time); - - /** - * Advance the timer - * - * @param time - * Duration in seconds to advance by - */ - public void advanceTimeInSecondsBy(double time); - -} diff --git a/src/main/java/xbot/common/controls/sensors/XTimer.java b/src/main/java/xbot/common/controls/sensors/XTimer.java deleted file mode 100644 index 67d4ce4f8..000000000 --- a/src/main/java/xbot/common/controls/sensors/XTimer.java +++ /dev/null @@ -1,40 +0,0 @@ -package xbot.common.controls.sensors; - -import org.wpilib.units.measure.Time; - -import static org.wpilib.units.Units.Seconds; - -public class XTimer { - private static XTimerImpl impl; - - public static void setImplementation(XTimerImpl implementation) { - impl = implementation; - } - - /** - * Returns the current time in seconds since the FPGA was powered on. - * - * @return Time in seconds - */ - public static double getFPGATimestamp() { - return impl.getFPGATimestamp(); - } - - /** - * Returns the current time in seconds since the FPGA was powered on. - * - * @return Time in seconds - */ - public static Time getFPGATimestampTime() { - return Seconds.of(impl.getFPGATimestamp()); - } - - public static double getMatchTime() { - return impl.getMatchTime(); - } - - public static void delay(double seconds) { - impl.delay(seconds); - } - -} diff --git a/src/main/java/xbot/common/controls/sensors/XTimerImpl.java b/src/main/java/xbot/common/controls/sensors/XTimerImpl.java deleted file mode 100644 index dc85a7ea7..000000000 --- a/src/main/java/xbot/common/controls/sensors/XTimerImpl.java +++ /dev/null @@ -1,9 +0,0 @@ -package xbot.common.controls.sensors; - -public interface XTimerImpl { - public double getFPGATimestamp(); - - public double getMatchTime(); - - public void delay(double seconds); -} diff --git a/src/main/java/xbot/common/controls/sensors/mock_adapters/MockLaserCAN.java b/src/main/java/xbot/common/controls/sensors/mock_adapters/MockLaserCAN.java index 3ab6ac887..58373c897 100644 --- a/src/main/java/xbot/common/controls/sensors/mock_adapters/MockLaserCAN.java +++ b/src/main/java/xbot/common/controls/sensors/mock_adapters/MockLaserCAN.java @@ -1,5 +1,7 @@ package xbot.common.controls.sensors.mock_adapters; +import org.wpilib.system.Timer; + import dagger.assisted.Assisted; import dagger.assisted.AssistedFactory; import dagger.assisted.AssistedInject; @@ -7,7 +9,6 @@ import xbot.common.command.DataFrameRegistry; import xbot.common.controls.io_inputs.LaserCANInputs; import xbot.common.controls.sensors.XLaserCAN; -import xbot.common.controls.sensors.XTimer; import xbot.common.injection.DevicePolice; import xbot.common.injection.electrical_contract.DeviceInfo; @@ -31,13 +32,13 @@ public MockLaserCAN(@Assisted("info") DeviceInfo info, @Assisted("owningSystemPr public void setDistance(double distanceMeters) { this.distanceMeters = distanceMeters; - this.measurementTime = XTimer.getFPGATimestamp(); + this.measurementTime = Timer.getMonotonicTimestamp(); } @Override public void updateInputs(LaserCANInputs inputs) { inputs.isMeasurementValid = true; inputs.distance = org.wpilib.units.Units.Meters.of(distanceMeters); - inputs.measurementLatency = Seconds.of(XTimer.getFPGATimestamp() - measurementTime); + inputs.measurementLatency = Seconds.of(Timer.getMonotonicTimestamp() - measurementTime); } } diff --git a/src/main/java/xbot/common/controls/sensors/mock_adapters/MockTimer.java b/src/main/java/xbot/common/controls/sensors/mock_adapters/MockTimer.java deleted file mode 100644 index b3c4a4b76..000000000 --- a/src/main/java/xbot/common/controls/sensors/mock_adapters/MockTimer.java +++ /dev/null @@ -1,47 +0,0 @@ -package xbot.common.controls.sensors.mock_adapters; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import xbot.common.controls.sensors.XSettableTimerImpl; - -@Singleton -public class MockTimer implements XSettableTimerImpl { - - @Inject - public MockTimer() { - } - - double timeInSeconds; - - @Override - public void setTimeInSeconds(double time) { - timeInSeconds = time; - } - - @Override - public void advanceTimeInSecondsBy(double time) { - timeInSeconds += time; - } - - /** - * Return the system clock time in seconds. Return the time from the FPGA hardware clock in seconds since the FPGA - * started. - * - * @return Robot running time in seconds. - */ - @Override - public double getFPGATimestamp() { - return timeInSeconds; - } - - @Override - public double getMatchTime() { - return timeInSeconds; - } - - @Override - public void delay(double seconds) { - - } -} diff --git a/src/main/java/xbot/common/controls/sensors/wpi_adapters/LaserCANWpiAdapter.java b/src/main/java/xbot/common/controls/sensors/wpi_adapters/LaserCANWpiAdapter.java index 48591409d..49681556a 100644 --- a/src/main/java/xbot/common/controls/sensors/wpi_adapters/LaserCANWpiAdapter.java +++ b/src/main/java/xbot/common/controls/sensors/wpi_adapters/LaserCANWpiAdapter.java @@ -9,9 +9,8 @@ * import dagger.assisted.Assisted; import dagger.assisted.AssistedFactory; import dagger.assisted.AssistedInject; * * import xbot.common.command.DataFrameRegistry; import xbot.common.controls.io_inputs.LaserCANInputs; import - * xbot.common.controls.sensors.XLaserCAN; import xbot.common.controls.sensors.XTimer; import - * xbot.common.injection.DevicePolice; import xbot.common.injection.electrical_contract.DeviceInfo; import - * xbot.common.logging.AlertGroups; + * xbot.common.controls.sensors.XLaserCAN; import org.wpilib.system.Timer; import xbot.common.injection.DevicePolice; + * import xbot.common.injection.electrical_contract.DeviceInfo; import xbot.common.logging.AlertGroups; * * import static org.wpilib.units.Units.Meters; import static org.wpilib.units.Units.Seconds; * @@ -41,8 +40,8 @@ * @Override public void updateInputs(LaserCANInputs inputs) { LaserCanInterface.Measurement measurement = * laserCan.getMeasurement(); if (measurement != null && measurement.status == * LaserCan.LASERCAN_STATUS_VALID_MEASUREMENT) { inputs.distance = Meters.of(measurement.distance_mm / 1000.0); if - * (!inputs.distance.isEquivalent(previousMeasurement)) { previousMeasurementTime = XTimer.getFPGATimestampTime(); - * previousMeasurement = inputs.distance; } inputs.measurementLatency = - * XTimer.getFPGATimestampTime().minus(previousMeasurementTime); inputs.isMeasurementValid = true; } else { + * (!inputs.distance.isEquivalent(previousMeasurement)) { previousMeasurementTime = + * Seconds.of(Timer.getMonotonicTimestamp()); previousMeasurement = inputs.distance; } inputs.measurementLatency = + * Seconds.of(Timer.getMonotonicTimestamp()).minus(previousMeasurementTime); inputs.isMeasurementValid = true; } else { * inputs.distance = Meters.zero(); inputs.measurementLatency = Seconds.zero(); inputs.isMeasurementValid = false; } } } */ diff --git a/src/main/java/xbot/common/controls/sensors/wpi_adapters/LidarLiteWpiAdapter.java b/src/main/java/xbot/common/controls/sensors/wpi_adapters/LidarLiteWpiAdapter.java index d88b16fd5..4183b7159 100644 --- a/src/main/java/xbot/common/controls/sensors/wpi_adapters/LidarLiteWpiAdapter.java +++ b/src/main/java/xbot/common/controls/sensors/wpi_adapters/LidarLiteWpiAdapter.java @@ -2,13 +2,13 @@ import org.wpilib.hardware.bus.I2C; import org.wpilib.hardware.bus.I2C.Port; +import org.wpilib.system.Timer; import dagger.assisted.Assisted; import dagger.assisted.AssistedFactory; import dagger.assisted.AssistedInject; import xbot.common.controls.sensors.XLidarLite; -import xbot.common.controls.sensors.XTimer; import xbot.common.injection.DevicePolice; import xbot.common.properties.TunableFactory; @@ -32,9 +32,9 @@ public LidarLiteWpiAdapter(@Assisted("port") Port port, TunableFactory tunableFa // Update distance variable public void update() { i2c.write(lidar_config_register, 0x04); // Initiate measurement - XTimer.delay(0.04); // Delay for measurement to be taken + Timer.delay(0.04); // Delay for measurement to be taken i2c.read(lidar_distance_register, 2, distance); // Read in measurement - XTimer.delay(0.01); // Delay to prevent over polling + Timer.delay(0.01); // Delay to prevent over polling } } diff --git a/src/main/java/xbot/common/controls/sensors/wpi_adapters/TimerWpiAdapter.java b/src/main/java/xbot/common/controls/sensors/wpi_adapters/TimerWpiAdapter.java deleted file mode 100644 index 38cc93918..000000000 --- a/src/main/java/xbot/common/controls/sensors/wpi_adapters/TimerWpiAdapter.java +++ /dev/null @@ -1,41 +0,0 @@ -package xbot.common.controls.sensors.wpi_adapters; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.wpilib.system.Timer; - -import xbot.common.controls.sensors.XSettableTimerImpl; - -@Singleton -public class TimerWpiAdapter implements XSettableTimerImpl { - - @Inject - public TimerWpiAdapter() { - } - - @Override - public double getFPGATimestamp() { - return Timer.getMonotonicTimestamp(); - } - - @Override - public double getMatchTime() { - return Timer.getMatchTime(); - } - - @Override - public void delay(double seconds) { - Timer.delay(seconds); - } - - @Override - public void setTimeInSeconds(double time) { - // Deliberately do nothing. - } - - @Override - public void advanceTimeInSecondsBy(double time) { - // Deliberately do nothing. - } -} diff --git a/src/main/java/xbot/common/injection/BaseWPITest.java b/src/main/java/xbot/common/injection/BaseWPITest.java index eef784d9f..97c08903b 100644 --- a/src/main/java/xbot/common/injection/BaseWPITest.java +++ b/src/main/java/xbot/common/injection/BaseWPITest.java @@ -4,11 +4,11 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; +import org.wpilib.hardware.hal.HAL; +import org.wpilib.simulation.SimHooks; import org.wpilib.tunable.MockTunableBackend; import org.wpilib.tunable.TunableRegistry; -import xbot.common.controls.sensors.XTimer; -import xbot.common.controls.sensors.mock_adapters.MockTimer; import xbot.common.injection.components.BaseComponent; import xbot.common.logging.assertion.RobotAssertionManager; import xbot.common.logging.assertion.SilentRobotAssertionHandler; @@ -24,8 +24,6 @@ public abstract class BaseWPITest { protected PIDManagerFactory pf; - protected MockTimer timer; - /** * Returns the {@link BaseComponent} instance used for dependency injection */ @@ -42,8 +40,9 @@ public void setUp() { TunableRegistry.registerBackend("", tunableBackend); injectorComponent = createDaggerComponent(); RobotAssertionManager.configure(injectorComponent.robotAssertionHandler()); - timer = (MockTimer) injectorComponent.timerImplementation(); - XTimer.setImplementation(timer); + // Freeze the simulated clock so time only moves when a test calls SimHooks.stepTiming(seconds). + HAL.initialize(); + SimHooks.pauseTiming(); tunableFactory = injectorComponent.tunableFactory(); @@ -52,6 +51,7 @@ public void setUp() { @AfterEach public void tearDownTunables() { + SimHooks.resumeTiming(); RobotAssertionManager.configure(new SilentRobotAssertionHandler()); TunableRegistry.reset(); } diff --git a/src/main/java/xbot/common/injection/components/BaseComponent.java b/src/main/java/xbot/common/injection/components/BaseComponent.java index 8a3218f65..124081c99 100644 --- a/src/main/java/xbot/common/injection/components/BaseComponent.java +++ b/src/main/java/xbot/common/injection/components/BaseComponent.java @@ -26,8 +26,6 @@ import xbot.common.controls.sensors.XLaserCAN; import xbot.common.controls.sensors.XLidarLite.XLidarLiteFactory; import xbot.common.controls.sensors.XPowerDistributionPanel.XPowerDistributionPanelFactory; -import xbot.common.controls.sensors.XSettableTimerImpl; -import xbot.common.controls.sensors.XTimerImpl; import xbot.common.controls.sensors.XXboxController.XXboxControllerFactory; import xbot.common.controls.sensors.buttons.AdvancedJoystickButtonTrigger.AdvancedJoystickButtonTriggerFactory; import xbot.common.controls.sensors.buttons.AdvancedPovButtonTrigger.AdvancedPovButtonTriggerFactory; @@ -60,10 +58,6 @@ */ @SuppressWarnings("unused") public abstract class BaseComponent { - public abstract XTimerImpl timerImplementation(); - - public abstract XSettableTimerImpl settableTimerImplementation(); - public abstract RobotAssertionHandler robotAssertionHandler(); public abstract DevicePolice devicePolice(); diff --git a/src/main/java/xbot/common/injection/modules/RobotModule.java b/src/main/java/xbot/common/injection/modules/RobotModule.java index fae7911cf..1898f4c8f 100644 --- a/src/main/java/xbot/common/injection/modules/RobotModule.java +++ b/src/main/java/xbot/common/injection/modules/RobotModule.java @@ -8,9 +8,6 @@ import xbot.common.command.RealTunableCommandPublisher; import xbot.common.command.TunableCommandPublisher; -import xbot.common.controls.sensors.XSettableTimerImpl; -import xbot.common.controls.sensors.XTimerImpl; -import xbot.common.controls.sensors.wpi_adapters.TimerWpiAdapter; import xbot.common.logging.assertion.RobotAssertionHandler; import xbot.common.logging.assertion.SilentRobotAssertionHandler; import xbot.common.properties.DebugTunablePersistence; @@ -25,14 +22,6 @@ */ @Module public abstract class RobotModule { - @Binds - @Singleton - abstract XTimerImpl getTimer(TimerWpiAdapter impl); - - @Binds - @Singleton - abstract XSettableTimerImpl getSettableTimer(TimerWpiAdapter impl); - @Binds @Singleton abstract TunablePersistence getTunablePersistence(PreferencesTunablePersistence impl); diff --git a/src/main/java/xbot/common/injection/modules/SimulationModule.java b/src/main/java/xbot/common/injection/modules/SimulationModule.java index 9f54d004c..2d1c6c05c 100644 --- a/src/main/java/xbot/common/injection/modules/SimulationModule.java +++ b/src/main/java/xbot/common/injection/modules/SimulationModule.java @@ -8,9 +8,6 @@ import xbot.common.command.RealTunableCommandPublisher; import xbot.common.command.TunableCommandPublisher; -import xbot.common.controls.sensors.XSettableTimerImpl; -import xbot.common.controls.sensors.XTimerImpl; -import xbot.common.controls.sensors.wpi_adapters.TimerWpiAdapter; import xbot.common.logging.assertion.LoudRobotAssertionHandler; import xbot.common.logging.assertion.RobotAssertionHandler; import xbot.common.properties.DebugTunablePersistence; @@ -25,14 +22,6 @@ */ @Module public abstract class SimulationModule { - @Binds - @Singleton - abstract XTimerImpl getTimer(TimerWpiAdapter impl); - - @Binds - @Singleton - abstract XSettableTimerImpl getSettableTimer(TimerWpiAdapter impl); - @Binds @Singleton abstract TunablePersistence getTunablePersistence(PreferencesTunablePersistence impl); diff --git a/src/main/java/xbot/common/injection/modules/UnitTestModule.java b/src/main/java/xbot/common/injection/modules/UnitTestModule.java index 588bd6ed9..dd2335f4a 100644 --- a/src/main/java/xbot/common/injection/modules/UnitTestModule.java +++ b/src/main/java/xbot/common/injection/modules/UnitTestModule.java @@ -8,9 +8,6 @@ import xbot.common.command.MockTunableCommandPublisher; import xbot.common.command.TunableCommandPublisher; -import xbot.common.controls.sensors.XSettableTimerImpl; -import xbot.common.controls.sensors.XTimerImpl; -import xbot.common.controls.sensors.mock_adapters.MockTimer; import xbot.common.logging.assertion.LoudRobotAssertionHandler; import xbot.common.logging.assertion.RobotAssertionHandler; import xbot.common.properties.DebugTunablePersistence; @@ -25,14 +22,6 @@ */ @Module public abstract class UnitTestModule { - @Binds - @Singleton - abstract XTimerImpl getTimer(MockTimer impl); - - @Binds - @Singleton - abstract XSettableTimerImpl getSettableTimer(MockTimer impl); - @Binds @Singleton abstract TunablePersistence getTunablePersistence(InMemoryTunablePersistence impl); diff --git a/src/main/java/xbot/common/logging/TimeLogger.java b/src/main/java/xbot/common/logging/TimeLogger.java index 95dc43e58..9f62d31a0 100644 --- a/src/main/java/xbot/common/logging/TimeLogger.java +++ b/src/main/java/xbot/common/logging/TimeLogger.java @@ -3,7 +3,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; public class TimeLogger { @@ -54,6 +54,6 @@ public void stop() { } private double getPerformanceTimestamp() { - return XTimer.getFPGATimestamp(); + return Timer.getMonotonicTimestamp(); } } diff --git a/src/main/java/xbot/common/logic/CalibrationDecider.java b/src/main/java/xbot/common/logic/CalibrationDecider.java index 3e0aafaa4..a7f5e708b 100644 --- a/src/main/java/xbot/common/logic/CalibrationDecider.java +++ b/src/main/java/xbot/common/logic/CalibrationDecider.java @@ -1,12 +1,12 @@ package xbot.common.logic; +import org.wpilib.system.Timer; import org.wpilib.tunable.TunableDouble; import dagger.assisted.Assisted; import dagger.assisted.AssistedFactory; import dagger.assisted.AssistedInject; -import xbot.common.controls.sensors.XTimer; import xbot.common.properties.TunableFactory; public class CalibrationDecider { @@ -31,7 +31,7 @@ public CalibrationDecider(@Assisted("name") String name, TunableFactory tunableF } public void reset() { - startTime = XTimer.getFPGATimestamp(); + startTime = Timer.getMonotonicTimestamp(); } public CalibrationMode decideMode(boolean isCalibrated) { @@ -39,7 +39,7 @@ public CalibrationMode decideMode(boolean isCalibrated) { return CalibrationMode.Calibrated; } - if (XTimer.getFPGATimestamp() - startTime > calibrationTimeTunable.get()) { + if (Timer.getMonotonicTimestamp() - startTime > calibrationTimeTunable.get()) { return CalibrationMode.GaveUp; } diff --git a/src/main/java/xbot/common/logic/FiniteStateMachine.java b/src/main/java/xbot/common/logic/FiniteStateMachine.java index 1653f1ace..074ac44be 100644 --- a/src/main/java/xbot/common/logic/FiniteStateMachine.java +++ b/src/main/java/xbot/common/logic/FiniteStateMachine.java @@ -3,7 +3,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; /** * A small, reusable, polled finite state machine, intended to be ticked once per robot loop from a @@ -211,16 +211,16 @@ public long getExecutionsInState() { } /** - * @return The number of seconds since the current state was entered, per {@link XTimer}. + * @return The number of seconds since the current state was entered, per {@link Timer}. */ public double getTimeInState() { - return XTimer.getFPGATimestamp() - timeStateStart; + return Timer.getMonotonicTimestamp() - timeStateStart; } private void ensureInitialized(ContextT payload, FsmTransition transition) { if (!initialized) { initialized = true; - timeStateStart = XTimer.getFPGATimestamp(); + timeStateStart = Timer.getMonotonicTimestamp(); currentState.enter(buildContext(payload), transition); } } @@ -236,13 +236,13 @@ private void changeState(StateT newState, ContextT payload) { previousState = oldState; oldState.exit(buildContext(payload), transition); currentState = newState; - timeStateStart = XTimer.getFPGATimestamp(); + timeStateStart = Timer.getMonotonicTimestamp(); executionsInState = 0; currentState.enter(buildContext(payload), transition); } private FsmContext buildContext(ContextT payload) { - return new FsmContext<>(payload, executionsInState, XTimer.getFPGATimestamp() - timeStateStart); + return new FsmContext<>(payload, executionsInState, Timer.getMonotonicTimestamp() - timeStateStart); } /** diff --git a/src/main/java/xbot/common/logic/FsmContext.java b/src/main/java/xbot/common/logic/FsmContext.java index 747a8d0de..497f67b2b 100644 --- a/src/main/java/xbot/common/logic/FsmContext.java +++ b/src/main/java/xbot/common/logic/FsmContext.java @@ -13,7 +13,7 @@ * The number of times {@link FiniteStateMachine#execute(Object)} has run against the current state, * including this call. Reset to zero whenever the state changes. * @param timeInState - * The number of seconds since the current state was entered, per {@code XTimer}. Reset to zero whenever the + * The number of seconds since the current state was entered, per {@code Timer}. Reset to zero whenever the * state changes. * @param * The type of the payload. diff --git a/src/main/java/xbot/common/logic/HumanVsMachineDecider.java b/src/main/java/xbot/common/logic/HumanVsMachineDecider.java index 4033557f8..d95db7af4 100644 --- a/src/main/java/xbot/common/logic/HumanVsMachineDecider.java +++ b/src/main/java/xbot/common/logic/HumanVsMachineDecider.java @@ -1,12 +1,12 @@ package xbot.common.logic; +import org.wpilib.system.Timer; import org.wpilib.tunable.TunableDouble; import dagger.assisted.Assisted; import dagger.assisted.AssistedFactory; import dagger.assisted.AssistedInject; -import xbot.common.controls.sensors.XTimer; import xbot.common.properties.TunableFactory; import xbot.common.properties.TunableLevel; @@ -74,7 +74,7 @@ public void reset() { public void reset(boolean startInAutomaticMode) { // No human input to report at reset time; lastHumanTime is pushed far enough into the past that a // coast check could never hold a fresh reset up. - payload = new HumanVsMachinePayload(0.0, deadbandTunable.get(), coastTimeTunable.get(), XTimer.getFPGATimestamp() - 100); + payload = new HumanVsMachinePayload(0.0, deadbandTunable.get(), coastTimeTunable.get(), Timer.getMonotonicTimestamp() - 100); fsm.forceState(startInAutomaticMode ? HumanVsMachineState.MachineControl : HumanVsMachineState.RobotDisabled, payload); } @@ -86,7 +86,7 @@ public void reset(boolean startInAutomaticMode) { * @return The recommended state. */ public HumanVsMachineState getRecommendedState(double humanInput) { - double lastHumanTime = Math.abs(humanInput) > deadbandTunable.get() ? XTimer.getFPGATimestamp() : payload.lastHumanTime(); + double lastHumanTime = Math.abs(humanInput) > deadbandTunable.get() ? Timer.getMonotonicTimestamp() : payload.lastHumanTime(); payload = new HumanVsMachinePayload(humanInput, deadbandTunable.get(), coastTimeTunable.get(), lastHumanTime); fsm.execute(payload); diff --git a/src/main/java/xbot/common/logic/HumanVsMachineState.java b/src/main/java/xbot/common/logic/HumanVsMachineState.java index 1ad9c1238..471f2ebfe 100644 --- a/src/main/java/xbot/common/logic/HumanVsMachineState.java +++ b/src/main/java/xbot/common/logic/HumanVsMachineState.java @@ -1,8 +1,7 @@ package xbot.common.logic; import org.wpilib.driverstation.RobotState; - -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; /** * The states of {@link HumanVsMachineDecider}'s internal state machine, in the order control moves through them: @@ -47,7 +46,7 @@ public void execute(FsmContext context, FsmTransition payload.deadband()) { return; // still actively controlled this tick; the beforeHook keeps re-asserting this state } - if (XTimer.getFPGATimestamp() - payload.lastHumanTime() < payload.coastTime()) { + if (Timer.getMonotonicTimestamp() - payload.lastHumanTime() < payload.coastTime()) { transition.transitionTo(Coast); } else { transition.transitionTo(InitializeMachineControl); @@ -58,7 +57,7 @@ public void execute(FsmContext context, FsmTransition context, FsmTransition transition) { var payload = context.payload(); - if (XTimer.getFPGATimestamp() - payload.lastHumanTime() >= payload.coastTime()) { + if (Timer.getMonotonicTimestamp() - payload.lastHumanTime() >= payload.coastTime()) { transition.transitionTo(InitializeMachineControl); } } diff --git a/src/main/java/xbot/common/logic/ReadMeFiniteStateMachine.md b/src/main/java/xbot/common/logic/ReadMeFiniteStateMachine.md index 697c2fb6f..d2f57fa9e 100644 --- a/src/main/java/xbot/common/logic/ReadMeFiniteStateMachine.md +++ b/src/main/java/xbot/common/logic/ReadMeFiniteStateMachine.md @@ -15,7 +15,7 @@ up every time: on every tick for as long as you're in that state. - **Manual timers that don't reset.** "Have we been in this state for 2 seconds?" usually gets answered with a hand-rolled `double stateStartTime` field, set (and often *forgotten to be reset*) at each - transition, then checked with `XTimer.getFPGATimestamp() - stateStartTime > threshold`. + transition, then checked with `Timer.getMonotonicTimestamp() - stateStartTime > threshold`. - **Duplicated bookkeeping.** The same "did we just enter this state?" check gets copy-pasted at every call site that can transition into that state. - **No clean place to test a single state in isolation**, because entry/exit/execute logic is all smeared @@ -298,8 +298,8 @@ What changed, concretely: check every cycle without worrying about re-triggering `Stall` once already in it - see `HumanVsMachineDecider`'s own `globalTransitions` hook for exactly this pattern. - **Testing:** construct the FSM with plain `new` (no dependency injection needed), drive it with a fake - `ContextT`, and advance time with the injected `MockTimer` (`timer.advanceTimeInSecondsBy(...)` in a test - extending `BaseCommonLibTest`) to exercise `timeInState()`-based transitions deterministically. + `ContextT`, and advance time with `SimHooks.stepTiming(...)` (in a test extending + `BaseCommonLibTest`, which pauses the simulated clock) to exercise `timeInState()`-based transitions deterministically. `FiniteStateMachineTest.java` has a full worked example doing exactly this (a light-switch FSM with a timed auto-off transition), plus tests covering entry/exit ordering, `beforeHook` preemption, and more. `FiniteStateMachineReadMeExampleTest.java` is the closer model for testing a real command: it ticks the diff --git a/src/main/java/xbot/common/logic/StallDetector.java b/src/main/java/xbot/common/logic/StallDetector.java index cf714f45d..2b8fb624c 100644 --- a/src/main/java/xbot/common/logic/StallDetector.java +++ b/src/main/java/xbot/common/logic/StallDetector.java @@ -1,12 +1,12 @@ package xbot.common.logic; +import org.wpilib.system.Timer; import org.wpilib.tunable.TunableDouble; import dagger.assisted.Assisted; import dagger.assisted.AssistedFactory; import dagger.assisted.AssistedInject; -import xbot.common.controls.sensors.XTimer; import xbot.common.properties.TunableFactory; public class StallDetector { @@ -94,7 +94,7 @@ public StallState getIsStalled(double current, double voltagePercent, double vel boolean noMotion = noMotionValidator.checkStable(Math.abs(velocity) < littleMotionThreshold.get() && voltageCondition); if (currentOverLimit || noMotion) { - timeOfLastDetectedStall = XTimer.getFPGATimestamp(); + timeOfLastDetectedStall = Timer.getMonotonicTimestamp(); return StallState.STALLED; } @@ -108,6 +108,6 @@ public StallState getIsStalled(double current, double voltagePercent, double vel } public boolean wasStalledRecently() { - return XTimer.getFPGATimestamp() - timeOfLastDetectedStall < stallCoolDown.get(); + return Timer.getMonotonicTimestamp() - timeOfLastDetectedStall < stallCoolDown.get(); } } diff --git a/src/main/java/xbot/common/logic/TimeStableValidator.java b/src/main/java/xbot/common/logic/TimeStableValidator.java index ef8a491c7..1e63a9243 100644 --- a/src/main/java/xbot/common/logic/TimeStableValidator.java +++ b/src/main/java/xbot/common/logic/TimeStableValidator.java @@ -2,7 +2,8 @@ import java.util.function.DoubleSupplier; -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; + import xbot.common.logic.Latch.EdgeType; /** @@ -40,7 +41,7 @@ public TimeStableValidator(DoubleSupplier stableWindowProvider) { private void initialize() { latch = new Latch(false, EdgeType.RisingEdge); - latch.setObserver((e) -> risingEdgeTime = XTimer.getFPGATimestamp()); + latch.setObserver((e) -> risingEdgeTime = Timer.getMonotonicTimestamp()); } /** @@ -79,7 +80,7 @@ private double getStableWindow() { */ public boolean checkStable(boolean value) { latch.setValue(value); - double duration = XTimer.getFPGATimestamp() - risingEdgeTime; + double duration = Timer.getMonotonicTimestamp() - risingEdgeTime; // if the value is true now, and has been for a while, it is stable. lastStableEvaluation = (duration > getStableWindow()) && value; return lastStableEvaluation; diff --git a/src/main/java/xbot/common/logic/WatchdogTimer.java b/src/main/java/xbot/common/logic/WatchdogTimer.java index a170be237..85c5cf546 100644 --- a/src/main/java/xbot/common/logic/WatchdogTimer.java +++ b/src/main/java/xbot/common/logic/WatchdogTimer.java @@ -1,6 +1,7 @@ package xbot.common.logic; -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; + import xbot.common.logic.Latch.EdgeType; public class WatchdogTimer { @@ -34,11 +35,11 @@ private void handleLatchUpdate(EdgeType edge) { } public void kick() { - lastKick = XTimer.getFPGATimestamp(); + lastKick = Timer.getMonotonicTimestamp(); } public void check() { - double now = XTimer.getFPGATimestamp(); + double now = Timer.getMonotonicTimestamp(); timeSinceKick = now - lastKick; isUp = Double.isFinite(timeSinceKick) && timeSinceKick <= timeout; latch.setValue(isUp); diff --git a/src/main/java/xbot/common/math/InterpolatingFieldPoseBuffer.java b/src/main/java/xbot/common/math/InterpolatingFieldPoseBuffer.java index 70e7f1278..ce8915c9e 100644 --- a/src/main/java/xbot/common/math/InterpolatingFieldPoseBuffer.java +++ b/src/main/java/xbot/common/math/InterpolatingFieldPoseBuffer.java @@ -1,8 +1,7 @@ package xbot.common.math; import org.wpilib.math.geometry.Rotation2d; - -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; public class InterpolatingFieldPoseBuffer { @@ -20,12 +19,12 @@ public InterpolatingFieldPoseBuffer(FieldPose pose) { } public void insert(FieldPose pose) { - xBuffer.insert(XTimer.getFPGATimestamp(), pose.getPoint().x); - yBuffer.insert(XTimer.getFPGATimestamp(), pose.getPoint().y); + xBuffer.insert(Timer.getMonotonicTimestamp(), pose.getPoint().x); + yBuffer.insert(Timer.getMonotonicTimestamp(), pose.getPoint().y); double headingDelta = pose.getHeading().minus(Rotation2d.fromDegrees(unwrappedHeading)).getDegrees(); unwrappedHeading += headingDelta; - headingBuffer.insert(XTimer.getFPGATimestamp(), unwrappedHeading); + headingBuffer.insert(Timer.getMonotonicTimestamp(), unwrappedHeading); } public FieldPose getPoseAtTime(double timeInSeconds) { diff --git a/src/main/java/xbot/common/math/InterpolatingHistoryBuffer.java b/src/main/java/xbot/common/math/InterpolatingHistoryBuffer.java index 65ea5022f..3bc1a96cd 100644 --- a/src/main/java/xbot/common/math/InterpolatingHistoryBuffer.java +++ b/src/main/java/xbot/common/math/InterpolatingHistoryBuffer.java @@ -8,7 +8,7 @@ import java.util.Arrays; -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; public class InterpolatingHistoryBuffer { @@ -31,7 +31,7 @@ public class InterpolatingHistoryBuffer { * Value to fill the inital samples with (probably zero is fine) */ public InterpolatingHistoryBuffer(int length, double init_val) { - double init_time = XTimer.getFPGATimestamp(); + double init_time = Timer.getMonotonicTimestamp(); value_buffer = new double[length]; time_buffer = new double[length]; Arrays.fill(value_buffer, init_val); diff --git a/src/main/java/xbot/common/math/PID.java b/src/main/java/xbot/common/math/PID.java index a3b276b7a..f557c95f8 100644 --- a/src/main/java/xbot/common/math/PID.java +++ b/src/main/java/xbot/common/math/PID.java @@ -2,7 +2,7 @@ import java.util.OptionalDouble; -import xbot.common.controls.sensors.XTimer; +import org.wpilib.system.Timer; /** * This PID was extracted from WPILib. It has all the same functionality, but does not run on its own separate thread. @@ -242,11 +242,11 @@ private void checkIsOnTarget() { if (onTarget) { if (waitingToStabilize == false) { waitingToStabilize = true; - startTime = XTimer.getFPGATimestamp(); + startTime = Timer.getMonotonicTimestamp(); onTarget = false; offTargetReason = OffTargetReason.NotTimeStable; } else { - onTarget = (XTimer.getFPGATimestamp() - startTime) > timeToleranceInSeconds; + onTarget = (Timer.getMonotonicTimestamp() - startTime) > timeToleranceInSeconds; offTargetReason = onTarget ? OffTargetReason.OnTarget : OffTargetReason.NotTimeStable; } } else { diff --git a/src/main/java/xbot/common/subsystems/drive/BaseSwerveDriveSubsystem.java b/src/main/java/xbot/common/subsystems/drive/BaseSwerveDriveSubsystem.java index cdf638eb9..005b0728f 100644 --- a/src/main/java/xbot/common/subsystems/drive/BaseSwerveDriveSubsystem.java +++ b/src/main/java/xbot/common/subsystems/drive/BaseSwerveDriveSubsystem.java @@ -14,13 +14,13 @@ import org.wpilib.math.kinematics.ChassisVelocities; import org.wpilib.math.kinematics.SwerveDriveKinematics; import org.wpilib.math.kinematics.SwerveModuleVelocity; +import org.wpilib.system.Timer; import org.wpilib.tunable.TunableDouble; import org.wpilib.units.measure.LinearAcceleration; import xbot.common.advantage.AKitLogger; import xbot.common.advantage.DataFrameRefreshable; import xbot.common.command.DataFrameRegistry; -import xbot.common.controls.sensors.XTimer; import xbot.common.injection.swerve.SwerveComponent; import xbot.common.math.PIDDefaults; import xbot.common.math.PIDManager; @@ -430,7 +430,7 @@ public void move(XYPair translate, double rotate, XYPair centerOfRotationInches) lastCommandedRotation = rotate; } - lastMoveCallTime = XTimer.getFPGATimestamp(); + lastMoveCallTime = Timer.getMonotonicTimestamp(); } public void setActivateBrakeOverride(boolean activateBrakeOverride) { diff --git a/src/main/java/xbot/common/subsystems/drive/control_logic/HeadingAssistModule.java b/src/main/java/xbot/common/subsystems/drive/control_logic/HeadingAssistModule.java index 1a21fbc88..c6a622139 100644 --- a/src/main/java/xbot/common/subsystems/drive/control_logic/HeadingAssistModule.java +++ b/src/main/java/xbot/common/subsystems/drive/control_logic/HeadingAssistModule.java @@ -3,13 +3,13 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.wpilib.system.Timer; import org.wpilib.tunable.TunableDouble; import dagger.assisted.Assisted; import dagger.assisted.AssistedFactory; import dagger.assisted.AssistedInject; -import xbot.common.controls.sensors.XTimer; import xbot.common.properties.TunableFactory; import xbot.common.subsystems.pose.BasePoseSubsystem; @@ -109,13 +109,13 @@ public double calculateHeadingPower(double humanRotationalPower) { // Also, update a timestamp that says this happened recently if (Math.abs(humanRotationalPower) > humanThreshold.get()) { inAutomaticMode = false; - lastHumanInput = XTimer.getFPGATimestamp(); + lastHumanInput = Timer.getMonotonicTimestamp(); return humanRotationalPower; } // If not under threshold, but too close to timestamp, // "coast" - double timeSinceHumanInput = XTimer.getFPGATimestamp() - lastHumanInput; + double timeSinceHumanInput = Timer.getMonotonicTimestamp() - lastHumanInput; if (timeSinceHumanInput < coastTime.get()) { return 0; diff --git a/src/main/java/xbot/common/subsystems/feedback/RumbleManager.java b/src/main/java/xbot/common/subsystems/feedback/RumbleManager.java index 757ef6ac0..f9e38f37e 100644 --- a/src/main/java/xbot/common/subsystems/feedback/RumbleManager.java +++ b/src/main/java/xbot/common/subsystems/feedback/RumbleManager.java @@ -2,13 +2,13 @@ import org.wpilib.driverstation.GenericHID; import org.wpilib.driverstation.GenericHID.RumbleType; +import org.wpilib.system.Timer; import dagger.assisted.Assisted; import dagger.assisted.AssistedFactory; import dagger.assisted.AssistedInject; import xbot.common.controls.sensors.XJoystick; -import xbot.common.controls.sensors.XTimer; /** * Wrappers around gamepad rumble behavior to control intensity and duration. @@ -41,7 +41,7 @@ public void stopGamepadRumble() { public void rumbleGamepad(double intensity, double length) { writeRumble(gamepad, intensity); - lastRequestEndTime = XTimer.getFPGATimestamp() + length; + lastRequestEndTime = Timer.getMonotonicTimestamp() + length; } public boolean getIsRumbling() { @@ -49,7 +49,7 @@ public boolean getIsRumbling() { } public void periodic() { - if (isRumbling && lastRequestEndTime > 0 && XTimer.getFPGATimestamp() > lastRequestEndTime) { + if (isRumbling && lastRequestEndTime > 0 && Timer.getMonotonicTimestamp() > lastRequestEndTime) { writeRumble(gamepad, 0); lastRequestEndTime = -1; isRumbling = false; diff --git a/src/main/java/xbot/common/subsystems/pose/BasePoseSubsystem.java b/src/main/java/xbot/common/subsystems/pose/BasePoseSubsystem.java index 965ea254a..c5ab57501 100644 --- a/src/main/java/xbot/common/subsystems/pose/BasePoseSubsystem.java +++ b/src/main/java/xbot/common/subsystems/pose/BasePoseSubsystem.java @@ -3,6 +3,7 @@ import org.wpilib.math.geometry.Pose2d; import org.wpilib.math.geometry.Rotation2d; import org.wpilib.math.util.MathUtil; +import org.wpilib.system.Timer; import org.wpilib.tunable.TunableBoolean; import org.wpilib.tunable.TunableDouble; import org.wpilib.units.measure.Angle; @@ -10,7 +11,6 @@ import xbot.common.command.BaseSubsystem; import xbot.common.controls.sensors.XGyro; import xbot.common.controls.sensors.XGyro.XGyroFactory; -import xbot.common.controls.sensors.XTimer; import xbot.common.math.FieldPose; import xbot.common.math.XYPair; import xbot.common.properties.TunableFactory; @@ -57,7 +57,7 @@ public BasePoseSubsystem(XGyro gyro, TunableFactory tunableFactory) { log.info("Creating"); tunableFactory.setPrefix(this); imu = gyro; - this.classInstantiationTime = XTimer.getFPGATimestamp(); + this.classInstantiationTime = Timer.getMonotonicTimestamp(); // Right when the system is initialized, we need to have the old value be // the same as the current value, to avoid any sudden changes later @@ -189,7 +189,7 @@ public void setCurrentHeading(double headingInDegrees) { headingOffset = -rawHeading + headingInDegrees; //log.info("Offset calculated to be: " + headingOffset); - lastSetHeadingTime = XTimer.getFPGATimestamp(); + lastSetHeadingTime = Timer.getMonotonicTimestamp(); } public void setCurrentPosition(double newXPosition, double newYPosition) { @@ -199,7 +199,7 @@ public void setCurrentPosition(double newXPosition, double newYPosition) { } public boolean getHeadingResetRecently() { - return XTimer.getFPGATimestamp() - lastSetHeadingTime < 1; + return Timer.getMonotonicTimestamp() - lastSetHeadingTime < 1; } /** @@ -264,7 +264,7 @@ public boolean getNavXReady() { @Override public void periodic() { - if (!isNavXReady && (classInstantiationTime + 1 < XTimer.getFPGATimestamp())) { + if (!isNavXReady && (classInstantiationTime + 1 < Timer.getMonotonicTimestamp())) { setCurrentHeading(FACING_AWAY_FROM_DRIVERS); isNavXReady = true; } diff --git a/src/main/java/xbot/common/trajectory/SimpleTimeInterpolator.java b/src/main/java/xbot/common/trajectory/SimpleTimeInterpolator.java index 357067459..82cabe64a 100644 --- a/src/main/java/xbot/common/trajectory/SimpleTimeInterpolator.java +++ b/src/main/java/xbot/common/trajectory/SimpleTimeInterpolator.java @@ -7,11 +7,11 @@ import org.wpilib.math.geometry.Rotation2d; import org.wpilib.math.geometry.Translation2d; +import org.wpilib.system.Timer; import org.wpilib.units.measure.Distance; import org.wpilib.units.measure.LinearVelocity; import xbot.common.advantage.AKitLogger; -import xbot.common.controls.sensors.XTimer; import xbot.common.subsystems.drive.SwerveKinematicsCalculator; import xbot.common.subsystems.drive.SwervePointKinematics; import xbot.common.subsystems.drive.SwerveSimpleTrajectoryMode; @@ -95,7 +95,7 @@ public void initialize(ProvidesInterpolationData baseline, SwerveSimpleTrajector log.debug("Initializing a SimpleTimeInterpolator"); this.baseline = baseline; accumulatedProductiveSeconds = 0; - previousTimestamp = XTimer.getFPGATimestamp(); + previousTimestamp = Timer.getMonotonicTimestamp(); index = 0; calculator = null; usingKinematics = (mode == SwerveSimpleTrajectoryMode.KinematicsForIndividualPoints) || (mode == SwerveSimpleTrajectoryMode.GlobalKinematicsValue); @@ -106,7 +106,7 @@ public SwerveKinematicsCalculator newCalculator(Translation2d targetPointTransla } public InterpolationResult calculateTarget(Translation2d currentLocation) { - double currentTime = XTimer.getFPGATimestamp(); + double currentTime = Timer.getMonotonicTimestamp(); aKitLog.record("CurrentTime", currentTime); double secondsSinceLastExecute = currentTime - previousTimestamp; diff --git a/src/test/java/xbot/common/command/BaseWaitForMaintainerCommandTest.java b/src/test/java/xbot/common/command/BaseWaitForMaintainerCommandTest.java index ad95bd667..8015fdff6 100644 --- a/src/test/java/xbot/common/command/BaseWaitForMaintainerCommandTest.java +++ b/src/test/java/xbot/common/command/BaseWaitForMaintainerCommandTest.java @@ -2,6 +2,8 @@ import org.junit.jupiter.api.Test; +import org.wpilib.simulation.SimHooks; + import xbot.common.injection.BaseCommonLibTest; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -33,7 +35,7 @@ public void testTimeout() { subsystem.setMaintainerIsAtGoal(false); assertFalse(command.isFinished()); - this.timer.advanceTimeInSecondsBy(10); + SimHooks.stepTiming(10); assertTrue(command.isFinished()); } diff --git a/src/test/java/xbot/common/command/RealTunableCommandPublisherTest.java b/src/test/java/xbot/common/command/RealTunableCommandPublisherTest.java index ce7e4dc9f..86a2e9e64 100644 --- a/src/test/java/xbot/common/command/RealTunableCommandPublisherTest.java +++ b/src/test/java/xbot/common/command/RealTunableCommandPublisherTest.java @@ -8,8 +8,6 @@ import org.wpilib.tunable.TunableRegistry; import org.wpilib.tunable.Tunables; -import xbot.common.controls.sensors.XTimer; -import xbot.common.controls.sensors.mock_adapters.MockTimer; import xbot.common.logging.assertion.RobotAssertionHandler; import xbot.common.logging.assertion.RobotAssertionManager; @@ -26,7 +24,6 @@ public void setUp() { TunableRegistry.reset(); tunableBackend = new MockTunableBackend(); TunableRegistry.registerBackend("", tunableBackend); - XTimer.setImplementation(new MockTimer()); } @AfterEach diff --git a/src/test/java/xbot/common/command/SimpleWaitForMaintainerCommandTest.java b/src/test/java/xbot/common/command/SimpleWaitForMaintainerCommandTest.java index 9da9dc3a0..efced5f89 100644 --- a/src/test/java/xbot/common/command/SimpleWaitForMaintainerCommandTest.java +++ b/src/test/java/xbot/common/command/SimpleWaitForMaintainerCommandTest.java @@ -2,6 +2,8 @@ import org.junit.jupiter.api.Test; +import org.wpilib.simulation.SimHooks; + import xbot.common.injection.BaseCommonLibTest; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -19,7 +21,7 @@ public void testTimeout() { command.execute(); assertFalse(command.isFinished()); - this.timer.advanceTimeInSecondsBy(1.5); + SimHooks.stepTiming(1.5); command.execute(); assertTrue(command.isFinished()); } @@ -37,7 +39,7 @@ public void testMaintainerAtGoal() { subsystem.setCurrentValue(0.0); subsystem.setMaintainerIsAtGoal(true); - this.timer.advanceTimeInSecondsBy(0.2); + SimHooks.stepTiming(0.2); command.execute(); assertTrue(command.isFinished()); } diff --git a/src/test/java/xbot/common/injection/MockTimerTest.java b/src/test/java/xbot/common/injection/MockTimerTest.java deleted file mode 100644 index 308924f65..000000000 --- a/src/test/java/xbot/common/injection/MockTimerTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package xbot.common.injection; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import org.wpilib.command2.Command; -import org.wpilib.command2.CommandScheduler; -import org.wpilib.command2.WaitCommand; - -import xbot.common.command.XScheduler; -import xbot.common.controls.sensors.mock_adapters.MockTimer; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class MockTimerTest extends BaseCommonLibTest { - - MockTimer timer; - - @BeforeEach - public void setup() { - timer = (MockTimer) getInjectorComponent().timerImplementation(); - } - - @Test - public void test_starts_zero() { - assertEquals(0.0, timer.getFPGATimestamp(), 0.001); - } - - @Test - public void updated_by_mock() { - timer.setTimeInSeconds(10.0); - assertEquals(10.0, timer.getFPGATimestamp(), 0.001); - } - - @Test - @Disabled("Changes to WPI's Timer render this non-functional, until we find a way to inject depeer into their library") - public void test_command_timed_out() { - Command timeOut = new WaitCommand(5); - XScheduler xScheduler = getInjectorComponent().scheduler(); - - CommandScheduler.getInstance().schedule(timeOut); - // Okay, so this is kind of weird. Basically, you need to call the scheduler twice for it - // to actually pull information about the timer from the mock timer. - xScheduler.run(); - xScheduler.run(); - // and currently, due to side effects from the Xscheduler tests, we need to run more times - // to clear evil commands or something. (CrashOnInit command is still running) - xScheduler.run(); - - timer.setTimeInSeconds(11.0); - assertTrue(timeOut.isFinished()); - } - -} diff --git a/src/test/java/xbot/common/logging/TimeLoggerTest.java b/src/test/java/xbot/common/logging/TimeLoggerTest.java index 702c644c4..4efa9f94a 100644 --- a/src/test/java/xbot/common/logging/TimeLoggerTest.java +++ b/src/test/java/xbot/common/logging/TimeLoggerTest.java @@ -3,6 +3,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.wpilib.simulation.SimHooks; + import xbot.common.injection.BaseCommonLibTest; public class TimeLoggerTest extends BaseCommonLibTest { @@ -21,20 +23,20 @@ public void setUp() { public void simpleTest() { tl.start(); - timer.advanceTimeInSecondsBy(2); + SimHooks.stepTiming(2); tl.stop(); } @Test public void testMultipleMeasurements() { tl.start(); - timer.advanceTimeInSecondsBy(0.25); + SimHooks.stepTiming(0.25); tl.stop(); - timer.advanceTimeInSecondsBy(1); + SimHooks.stepTiming(1); tl.start(); - timer.advanceTimeInSecondsBy(0.75); + SimHooks.stepTiming(0.75); tl.stop(); } diff --git a/src/test/java/xbot/common/logic/CalibrationDeciderTest.java b/src/test/java/xbot/common/logic/CalibrationDeciderTest.java index b51d749d7..788c51a71 100644 --- a/src/test/java/xbot/common/logic/CalibrationDeciderTest.java +++ b/src/test/java/xbot/common/logic/CalibrationDeciderTest.java @@ -3,7 +3,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import xbot.common.controls.sensors.XTimer; +import org.wpilib.simulation.SimHooks; +import org.wpilib.system.Timer; + import xbot.common.injection.BaseCommonLibTest; import xbot.common.properties.TunableFactory; @@ -28,12 +30,12 @@ public void testConstructor() { @Test public void testReset() { - timer.advanceTimeInSecondsBy(1); + SimHooks.stepTiming(1); decider.reset(); double beforeReset = decider.startTime; - timer.advanceTimeInSecondsBy(1); + SimHooks.stepTiming(1); decider.reset(); assertNotEquals(beforeReset, decider.startTime, 0.001); } @@ -45,13 +47,13 @@ public void testDecideModeWhenCalibrated() { @Test public void testDecideModeWhenTimeExceeded() { - decider.startTime = XTimer.getFPGATimestamp() - 4; // 4 is greater than the default calibrationTimeTunable value of 3 + decider.startTime = Timer.getMonotonicTimestamp() - 4; // 4 is greater than the default calibrationTimeTunable value of 3 assertEquals(CalibrationDecider.CalibrationMode.GaveUp, decider.decideMode(false)); } @Test public void testDecideModeWhenAttempting() { - decider.startTime = XTimer.getFPGATimestamp(); + decider.startTime = Timer.getMonotonicTimestamp(); assertEquals(CalibrationDecider.CalibrationMode.Attempting, decider.decideMode(false)); } } diff --git a/src/test/java/xbot/common/logic/FiniteStateMachineReadMeExampleTest.java b/src/test/java/xbot/common/logic/FiniteStateMachineReadMeExampleTest.java index 973037a9f..36fd1cbb8 100644 --- a/src/test/java/xbot/common/logic/FiniteStateMachineReadMeExampleTest.java +++ b/src/test/java/xbot/common/logic/FiniteStateMachineReadMeExampleTest.java @@ -7,8 +7,9 @@ import org.wpilib.math.geometry.Pose2d; import org.wpilib.math.geometry.Rotation2d; +import org.wpilib.simulation.SimHooks; +import org.wpilib.system.Timer; -import xbot.common.controls.sensors.XTimer; import xbot.common.injection.BaseCommonLibTest; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -211,14 +212,14 @@ record Phase(String state, double durationSeconds) { /** * Ticks a freshly-{@code initialize()}'d command at 50Hz until {@code isFinished()}, recording how long it spent in * each state along the way. This is deliberately measured against an independent clock (state-name transitions - * timestamped via {@link XTimer}) rather than by reading {@code cmd.fsm.getTimeInState()}: that keeps this check honest + * timestamped via {@link Timer}) rather than by reading {@code cmd.fsm.getTimeInState()}: that keeps this check honest * even against a bug in {@code getTimeInState()} itself, such as a reset that doesn't fire on every transition. */ private List runToCompletion(CalibrateDriveCommand cmd) { List phases = new ArrayList<>(); cmd.initialize(); String currentPhase = null; - double phaseStart = XTimer.getFPGATimestamp(); + double phaseStart = Timer.getMonotonicTimestamp(); for (int tick = 0; tick < MAX_TICKS; tick++) { cmd.execute(); @@ -226,15 +227,15 @@ private List runToCompletion(CalibrateDriveCommand cmd) { if (currentPhase == null) { currentPhase = observed; } else if (!observed.equals(currentPhase)) { - phases.add(new Phase(currentPhase, XTimer.getFPGATimestamp() - phaseStart)); + phases.add(new Phase(currentPhase, Timer.getMonotonicTimestamp() - phaseStart)); currentPhase = observed; - phaseStart = XTimer.getFPGATimestamp(); + phaseStart = Timer.getMonotonicTimestamp(); } if (cmd.isFinished()) { - phases.add(new Phase(currentPhase, XTimer.getFPGATimestamp() - phaseStart)); + phases.add(new Phase(currentPhase, Timer.getMonotonicTimestamp() - phaseStart)); return phases; } - timer.advanceTimeInSecondsBy(LOOP_PERIOD_SECONDS); + SimHooks.stepTiming(LOOP_PERIOD_SECONDS); } throw new AssertionError("Calibration never finished; stuck in " + currentPhase); } @@ -267,7 +268,7 @@ public void fsmVersionCapturesStartPositionsOnceAtEntry() { for (int tick = 0; tick < 50; tick++) { cmd.execute(); cmd.drive.advanceAllModulePositionsBy(1.0); - timer.advanceTimeInSecondsBy(LOOP_PERIOD_SECONDS); + SimHooks.stepTiming(LOOP_PERIOD_SECONDS); } assertEquals(150.0, cmd.drive.frontLeft.driveMotorPosition, 1e-9, "the modules should have crept"); @@ -333,23 +334,23 @@ public void eachPhaseCommandsTheSpeedItsStateIsResponsibleFor() { assertEquals(0.0, cmd.drive.lastCommandedSpeed(), 1e-9); assertTrue(cmd.deltaLogs.isEmpty(), "the align phase should not be logging deltas yet"); - timer.advanceTimeInSecondsBy(2.5); + SimHooks.stepTiming(2.5); cmd.execute(); assertEquals(CalibrationState.DriveForwardForTime, cmd.fsm.getCurrentState()); assertEquals(0.0, cmd.drive.lastCommandedSpeed(), 1e-9, "AlignModulesAndWait's body finished before it asked for the transition"); assertTrue(cmd.deltaLogs.isEmpty(), "DriveForwardForTime's body has not run yet"); - timer.advanceTimeInSecondsBy(LOOP_PERIOD_SECONDS); + SimHooks.stepTiming(LOOP_PERIOD_SECONDS); cmd.execute(); assertEquals(1.5, cmd.drive.lastCommandedSpeed(), 1e-9); assertFalse(cmd.deltaLogs.isEmpty(), "the driving phase should be logging deltas"); - timer.advanceTimeInSecondsBy(8.5); + SimHooks.stepTiming(8.5); cmd.execute(); assertEquals(CalibrationState.DecelerateAndWait, cmd.fsm.getCurrentState()); assertEquals(1.5, cmd.drive.lastCommandedSpeed(), 1e-9, "same rule on the way out - this tick ran DriveForwardForTime's body first"); - timer.advanceTimeInSecondsBy(LOOP_PERIOD_SECONDS); + SimHooks.stepTiming(LOOP_PERIOD_SECONDS); cmd.execute(); assertEquals(0.0, cmd.drive.lastCommandedSpeed(), 1e-9); } @@ -359,16 +360,18 @@ public void eachPhaseCommandsTheSpeedItsStateIsResponsibleFor() { public void isFinishedOnlyOnceFinalAnalysisIsReached() { CalibrateDriveCommand cmd = new CalibrateDriveCommand(); cmd.initialize(); + double startTime = Timer.getMonotonicTimestamp(); for (int tick = 0; tick < MAX_TICKS; tick++) { cmd.execute(); if (cmd.isFinished()) { assertEquals(CalibrationState.FinalAnalysis, cmd.fsm.getCurrentState()); - assertEquals(15.0, XTimer.getFPGATimestamp(), DURATION_TOLERANCE_SECONDS); + // Three timed states, each with its own tick of slack. + assertEquals(15.0, Timer.getMonotonicTimestamp() - startTime, 3 * DURATION_TOLERANCE_SECONDS); return; } assertFalse(cmd.fsm.isInState(CalibrationState.FinalAnalysis)); - timer.advanceTimeInSecondsBy(LOOP_PERIOD_SECONDS); + SimHooks.stepTiming(LOOP_PERIOD_SECONDS); } throw new AssertionError("isFinished() never became true"); } diff --git a/src/test/java/xbot/common/logic/FiniteStateMachineTest.java b/src/test/java/xbot/common/logic/FiniteStateMachineTest.java index da31f7cfe..962fe5f6a 100644 --- a/src/test/java/xbot/common/logic/FiniteStateMachineTest.java +++ b/src/test/java/xbot/common/logic/FiniteStateMachineTest.java @@ -10,6 +10,8 @@ import org.apache.logging.log4j.core.config.Property; import org.junit.jupiter.api.Test; +import org.wpilib.simulation.SimHooks; + import xbot.common.injection.BaseCommonLibTest; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -129,12 +131,12 @@ public void bookkeepingIncrementsAcrossExecutions() { assertEquals(1, fsm.getExecutionsInState()); assertEquals(0.0, fsm.getTimeInState(), 0.0001); - timer.advanceTimeInSecondsBy(0.5); + SimHooks.stepTiming(0.5); fsm.execute(payload); assertEquals(2, fsm.getExecutionsInState()); assertEquals(0.5, fsm.getTimeInState(), 0.0001); - timer.advanceTimeInSecondsBy(0.25); + SimHooks.stepTiming(0.25); fsm.execute(payload); assertEquals(3, fsm.getExecutionsInState()); assertEquals(0.75, fsm.getTimeInState(), 0.0001); @@ -146,7 +148,7 @@ public void transitionRunsExitThenEnterAndResetsCounters() { payload.shouldTransitionAtoB = true; FiniteStateMachine fsm = new FiniteStateMachine<>("Test", TestState.A); - timer.advanceTimeInSecondsBy(1.0); + SimHooks.stepTiming(1.0); fsm.execute(payload); assertEquals(List.of("A.enter", "A.execute", "A.exit", "B.enter"), payload.events); @@ -306,13 +308,13 @@ public void beforeHookRepeatedlyRequestingSameStateDoesNotResetTimeInState() { assertEquals(TestState.Fault, fsm.getCurrentState()); assertEquals(0.0, fsm.getTimeInState(), 0.0001); - timer.advanceTimeInSecondsBy(1.0); + SimHooks.stepTiming(1.0); fsm.execute(payload); assertEquals(TestState.Fault, fsm.getCurrentState()); assertEquals(1.0, fsm.getTimeInState(), 0.0001, "the repeated same-state request from beforeHook should not have reset the clock"); - timer.advanceTimeInSecondsBy(1.0); + SimHooks.stepTiming(1.0); fsm.execute(payload); assertEquals(2.0, fsm.getTimeInState(), 0.0001); @@ -546,11 +548,11 @@ public void endToEndLightSwitchExample() { assertEquals(LightSwitchState.TimedOn, fsm.getCurrentState()); payload.flippedOn = false; - timer.advanceTimeInSecondsBy(1.0); + SimHooks.stepTiming(1.0); fsm.execute(payload); assertEquals(LightSwitchState.TimedOn, fsm.getCurrentState()); - timer.advanceTimeInSecondsBy(1.5); + SimHooks.stepTiming(1.5); fsm.execute(payload); assertEquals(LightSwitchState.Off, fsm.getCurrentState()); assertFalse(payload.lightOn); diff --git a/src/test/java/xbot/common/logic/HumanVsMachineDeciderTest.java b/src/test/java/xbot/common/logic/HumanVsMachineDeciderTest.java index 0389859a6..2fcaa357f 100644 --- a/src/test/java/xbot/common/logic/HumanVsMachineDeciderTest.java +++ b/src/test/java/xbot/common/logic/HumanVsMachineDeciderTest.java @@ -5,6 +5,7 @@ import org.junit.jupiter.api.Test; import org.wpilib.simulation.DriverStationSim; +import org.wpilib.simulation.SimHooks; import xbot.common.injection.BaseCommonLibTest; @@ -43,9 +44,9 @@ public void testStandardPath() { assertSame(HumanVsMachineState.MachineControl, decider.getRecommendedState(0), "Machine Control"); assertSame(HumanVsMachineState.HumanControl, decider.getRecommendedState(1), "Human input brings us back out"); - timer.advanceTimeInSecondsBy(0.01); + SimHooks.stepTiming(0.01); assertSame(HumanVsMachineState.Coast, decider.getRecommendedState(0.01), "Then we coast"); - timer.advanceTimeInSecondsBy(1); + SimHooks.stepTiming(1); assertSame(HumanVsMachineState.InitializeMachineControl, decider.getRecommendedState(0), "Advance to initialize"); assertSame(HumanVsMachineState.MachineControl, decider.getRecommendedState(0), "Machine Control"); } @@ -65,20 +66,20 @@ public void testRenewedHumanInputInterruptsCoastAndRestartsTimer() { assertSame(HumanVsMachineState.HumanControl, decider.getRecommendedState(1), "Human input brings us back out"); - timer.advanceTimeInSecondsBy(0.1); + SimHooks.stepTiming(0.1); assertSame(HumanVsMachineState.Coast, decider.getRecommendedState(0), "Input stopped, start coasting"); - timer.advanceTimeInSecondsBy(0.1); + SimHooks.stepTiming(0.1); assertSame(HumanVsMachineState.HumanControl, decider.getRecommendedState(1), "Fresh input mid-coast interrupts it and returns to human control"); // Only 0.1s has elapsed since the renewed input above, well under the 0.3s default coast time. If the // coast timer hadn't actually restarted - e.g. still measuring from the very first burst of input, // 0.2s + 0.1s = 0.3s ago - this would incorrectly already be eligible to leave Coast. - timer.advanceTimeInSecondsBy(0.1); + SimHooks.stepTiming(0.1); assertSame(HumanVsMachineState.Coast, decider.getRecommendedState(0), "Still within the coast window measured from the renewed input"); // Now push well past the coast window measured from the renewed input (0.1s + 0.3s = 0.4s total). - timer.advanceTimeInSecondsBy(0.3); + SimHooks.stepTiming(0.3); assertSame(HumanVsMachineState.InitializeMachineControl, decider.getRecommendedState(0), "Coast window (from the renewed input) has elapsed"); assertSame(HumanVsMachineState.MachineControl, decider.getRecommendedState(0), "Back to machine control"); } @@ -100,7 +101,7 @@ public void testHumanControlSkipsCoastWhenGracePeriodAlreadyElapsed() { // Advance well past the default 0.3s coast time before the next poll, rather than advancing by less // than it (as testStandardPath does) - simulating a gap longer than the coast window itself. - timer.advanceTimeInSecondsBy(1); + SimHooks.stepTiming(1); assertSame(HumanVsMachineState.InitializeMachineControl, decider.getRecommendedState(0), "Grace period already elapsed; skip straight past Coast"); assertSame(HumanVsMachineState.MachineControl, decider.getRecommendedState(0), "Machine Control"); } diff --git a/src/test/java/xbot/common/logic/StallDetectorTest.java b/src/test/java/xbot/common/logic/StallDetectorTest.java index fdff9da80..e309c0dd7 100644 --- a/src/test/java/xbot/common/logic/StallDetectorTest.java +++ b/src/test/java/xbot/common/logic/StallDetectorTest.java @@ -3,6 +3,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.wpilib.simulation.SimHooks; + import xbot.common.injection.BaseCommonLibTest; import xbot.common.logic.StallDetector.StallState; @@ -31,18 +33,18 @@ public void testCurrentStallConditions() { // Way over current limit assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(100, 0, 0)); // Needs to be that way for a little while - timer.advanceTimeInSecondsBy(1.1); + SimHooks.stepTiming(1.1); assertEquals(StallState.STALLED, stallDetector.getIsStalled(100, 0, 0)); - timer.advanceTimeInSecondsBy(0.1); + SimHooks.stepTiming(0.1); assertEquals(StallState.STALLED, stallDetector.getIsStalled(100, 0, 0)); // Now, stop forcing the mechanism assertEquals(StallState.WAS_STALLED_RECENTLY, stallDetector.getIsStalled(0, 0, 0)); // Wait a while - timer.advanceTimeInSecondsBy(1.9); + SimHooks.stepTiming(1.9); assertEquals(StallState.WAS_STALLED_RECENTLY, stallDetector.getIsStalled(0, 0, 0)); // Wait across the stall cool down - timer.advanceTimeInSecondsBy(0.2); + SimHooks.stepTiming(0.2); assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, 0, 0)); } @@ -50,13 +52,13 @@ public void testCurrentStallConditions() { public void testMotionStallConditions() { // Large voltage but no motion assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, 1, 0)); - timer.advanceTimeInSecondsBy(1.1); + SimHooks.stepTiming(1.1); assertEquals(StallState.STALLED, stallDetector.getIsStalled(0, 1, 0)); // Stop applying voltage, but only go forwards in time a little - timer.advanceTimeInSecondsBy(0.1); + SimHooks.stepTiming(0.1); assertEquals(StallState.WAS_STALLED_RECENTLY, stallDetector.getIsStalled(0, 0, 0)); // Wait a while for the system to cool down - timer.advanceTimeInSecondsBy(2.5); + SimHooks.stepTiming(2.5); assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, 0, 0)); } @@ -64,33 +66,33 @@ public void testMotionStallConditions() { public void testNegativeVoltageMotionStallConditions() { // Large voltage but no motion assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, -1, 0)); - timer.advanceTimeInSecondsBy(1.1); + SimHooks.stepTiming(1.1); assertEquals(StallState.STALLED, stallDetector.getIsStalled(0, -1, 0)); // Stop applying voltage, but only go forwards in time a little - timer.advanceTimeInSecondsBy(0.1); + SimHooks.stepTiming(0.1); assertEquals(StallState.WAS_STALLED_RECENTLY, stallDetector.getIsStalled(0, 0, 0)); // Wait a while for the system to cool down - timer.advanceTimeInSecondsBy(2.5); + SimHooks.stepTiming(2.5); assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, 0, 0)); } @Test public void testNormalMotion() { assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, 1, 100)); - timer.advanceTimeInSecondsBy(1.5); + SimHooks.stepTiming(1.5); assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, 1, 100)); - timer.advanceTimeInSecondsBy(1.5); + SimHooks.stepTiming(1.5); assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, 1, 100)); - timer.advanceTimeInSecondsBy(1.5); + SimHooks.stepTiming(1.5); assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, 1, 100)); - timer.advanceTimeInSecondsBy(50); + SimHooks.stepTiming(50); assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, -1, -100)); - timer.advanceTimeInSecondsBy(1.5); + SimHooks.stepTiming(1.5); assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, -1, -100)); - timer.advanceTimeInSecondsBy(1.5); + SimHooks.stepTiming(1.5); assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, -1, -100)); - timer.advanceTimeInSecondsBy(1.5); + SimHooks.stepTiming(1.5); assertEquals(StallState.NOT_STALLED, stallDetector.getIsStalled(0, -1, -100)); } diff --git a/src/test/java/xbot/common/logic/TimeStableValidatorTest.java b/src/test/java/xbot/common/logic/TimeStableValidatorTest.java index 54abc41cb..0aa40bd61 100644 --- a/src/test/java/xbot/common/logic/TimeStableValidatorTest.java +++ b/src/test/java/xbot/common/logic/TimeStableValidatorTest.java @@ -3,6 +3,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.wpilib.simulation.SimHooks; + import xbot.common.injection.BaseCommonLibTest; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -24,11 +26,11 @@ public void simpleTest() { boolean result = tsv.checkStable(true); assertFalse(result); - timer.advanceTimeInSecondsBy(0.5); + SimHooks.stepTiming(0.5); result = tsv.checkStable(true); assertFalse(result); - timer.advanceTimeInSecondsBy(0.6); + SimHooks.stepTiming(0.6); result = tsv.checkStable(true); assertTrue(result); } @@ -46,15 +48,15 @@ public void trueFalseTrue() { boolean result = tsv.checkStable(true); assertFalse(result); - timer.advanceTimeInSecondsBy(0.5); + SimHooks.stepTiming(0.5); result = tsv.checkStable(false); assertFalse(result); - timer.advanceTimeInSecondsBy(0.6); + SimHooks.stepTiming(0.6); result = tsv.checkStable(true); assertFalse(result); - timer.advanceTimeInSecondsBy(1.1); + SimHooks.stepTiming(1.1); result = tsv.checkStable(true); assertTrue(result); } @@ -64,7 +66,7 @@ public void stableThenUnstable() { boolean result = tsv.checkStable(true); assertFalse(result); - timer.advanceTimeInSecondsBy(1.1); + SimHooks.stepTiming(1.1); result = tsv.checkStable(true); assertTrue(result); @@ -74,7 +76,7 @@ public void stableThenUnstable() { result = tsv.checkStable(true); assertFalse(result); - timer.advanceTimeInSecondsBy(1.1); + SimHooks.stepTiming(1.1); result = tsv.checkStable(true); assertTrue(result); } diff --git a/src/test/java/xbot/common/logic/WatchdogTimerTest.java b/src/test/java/xbot/common/logic/WatchdogTimerTest.java index 3101fb7ec..c37c5af38 100644 --- a/src/test/java/xbot/common/logic/WatchdogTimerTest.java +++ b/src/test/java/xbot/common/logic/WatchdogTimerTest.java @@ -3,6 +3,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.wpilib.simulation.SimHooks; + import xbot.common.injection.BaseCommonLibTest; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -27,7 +29,7 @@ public void testBasic() { assertEquals(0, upCount); assertEquals(0, downCount); - timer.advanceTimeInSecondsBy(10); + SimHooks.stepTiming(10); watchdog.check(); assertEquals(0, upCount); @@ -39,13 +41,13 @@ public void testBasic() { assertEquals(1, upCount); assertEquals(0, downCount); - timer.advanceTimeInSecondsBy(4); + SimHooks.stepTiming(4); watchdog.check(); assertEquals(1, upCount); assertEquals(0, downCount); - timer.advanceTimeInSecondsBy(1.5); + SimHooks.stepTiming(1.5); watchdog.check(); assertEquals(1, upCount); @@ -58,7 +60,7 @@ public void testSustained() { assertEquals(0, upCount); assertEquals(0, downCount); - timer.advanceTimeInSecondsBy(1); + SimHooks.stepTiming(1); watchdog.kick(); @@ -66,26 +68,26 @@ public void testSustained() { assertEquals(1, upCount); assertEquals(0, downCount); - timer.advanceTimeInSecondsBy(1); + SimHooks.stepTiming(1); watchdog.check(); assertEquals(1, upCount); assertEquals(0, downCount); - timer.advanceTimeInSecondsBy(3); + SimHooks.stepTiming(3); watchdog.kick(); watchdog.check(); assertEquals(1, upCount); assertEquals(0, downCount); - timer.advanceTimeInSecondsBy(3); + SimHooks.stepTiming(3); watchdog.check(); assertEquals(1, upCount); assertEquals(0, downCount); - timer.advanceTimeInSecondsBy(3); + SimHooks.stepTiming(3); watchdog.check(); assertEquals(1, upCount); @@ -98,7 +100,7 @@ public void testRepeated() { assertEquals(0, upCount); assertEquals(0, downCount); - timer.advanceTimeInSecondsBy(5); + SimHooks.stepTiming(5); watchdog.kick(); @@ -106,20 +108,20 @@ public void testRepeated() { assertEquals(1, upCount); assertEquals(0, downCount); - timer.advanceTimeInSecondsBy(6); + SimHooks.stepTiming(6); watchdog.check(); assertEquals(1, upCount); assertEquals(1, downCount); - timer.advanceTimeInSecondsBy(1.5); + SimHooks.stepTiming(1.5); watchdog.kick(); watchdog.check(); assertEquals(2, upCount); assertEquals(1, downCount); - timer.advanceTimeInSecondsBy(6); + SimHooks.stepTiming(6); watchdog.check(); assertEquals(2, upCount); diff --git a/src/test/java/xbot/common/math/HistoryBufferTests.java b/src/test/java/xbot/common/math/HistoryBufferTests.java index 83c087608..15ee1d6c0 100644 --- a/src/test/java/xbot/common/math/HistoryBufferTests.java +++ b/src/test/java/xbot/common/math/HistoryBufferTests.java @@ -2,7 +2,9 @@ import org.junit.jupiter.api.Test; -import xbot.common.controls.sensors.XTimer; +import org.wpilib.simulation.SimHooks; +import org.wpilib.system.Timer; + import xbot.common.injection.BaseCommonLibTest; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -11,31 +13,34 @@ public class HistoryBufferTests extends BaseCommonLibTest { @Test public void simpleBufferTest() { + double start = Timer.getMonotonicTimestamp(); InterpolatingHistoryBuffer b = new InterpolatingHistoryBuffer(3, 5); - timer.advanceTimeInSecondsBy(2); - b.insert(XTimer.getFPGATimestamp(), 10); - assertEquals(7.5, b.getValAtTime(1), 0.001); + SimHooks.stepTiming(2); + b.insert(Timer.getMonotonicTimestamp(), 10); + assertEquals(7.5, b.getValAtTime(start + 1), 0.001); } @Test public void simplePoseBufferTest() { + double start = Timer.getMonotonicTimestamp(); FieldPose startingPose = new FieldPose(0, 0, 90); InterpolatingFieldPoseBuffer b = new InterpolatingFieldPoseBuffer(startingPose); - timer.advanceTimeInSecondsBy(1); + SimHooks.stepTiming(1); b.insert(new FieldPose(20, 20, 180)); - assertEquals(10, b.getPoseAtTime(0.5).getPoint().x, 0.001); - assertEquals(10, b.getPoseAtTime(0.5).getPoint().y, 0.001); - assertEquals(135, b.getPoseAtTime(0.5).getHeading().getDegrees(), 0.001); + assertEquals(10, b.getPoseAtTime(start + 0.5).getPoint().x, 0.001); + assertEquals(10, b.getPoseAtTime(start + 0.5).getPoint().y, 0.001); + assertEquals(135, b.getPoseAtTime(start + 0.5).getHeading().getDegrees(), 0.001); } @Test public void acrossBoundaryTest() { + double start = Timer.getMonotonicTimestamp(); FieldPose startingPose = new FieldPose(0, 0, 140); InterpolatingFieldPoseBuffer b = new InterpolatingFieldPoseBuffer(startingPose); - timer.advanceTimeInSecondsBy(1); + SimHooks.stepTiming(1); b.insert(new FieldPose(20, 20, -130)); - assertEquals(10, b.getPoseAtTime(0.5).getPoint().x, 0.001); - assertEquals(10, b.getPoseAtTime(0.5).getPoint().y, 0.001); - assertEquals(-175, b.getPoseAtTime(0.5).getHeading().getDegrees(), 0.001); + assertEquals(10, b.getPoseAtTime(start + 0.5).getPoint().x, 0.001); + assertEquals(10, b.getPoseAtTime(start + 0.5).getPoint().y, 0.001); + assertEquals(-175, b.getPoseAtTime(start + 0.5).getHeading().getDegrees(), 0.001); } } diff --git a/src/test/java/xbot/common/math/PIDManagerTest.java b/src/test/java/xbot/common/math/PIDManagerTest.java index 5386bb50e..da9c2f5bb 100644 --- a/src/test/java/xbot/common/math/PIDManagerTest.java +++ b/src/test/java/xbot/common/math/PIDManagerTest.java @@ -3,7 +3,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import xbot.common.controls.sensors.mock_adapters.MockTimer; +import org.wpilib.simulation.SimHooks; + import xbot.common.injection.BaseCommonLibTest; import xbot.common.logging.assertion.RobotAssertionException; import xbot.common.math.PID.OffTargetReason; @@ -17,13 +18,11 @@ public class PIDManagerTest extends BaseCommonLibTest { PIDManagerFactory factory; - MockTimer mockTimer; @BeforeEach public void setUp() { super.setUp(); factory = getInjectorComponent().pidFactory(); - mockTimer = (MockTimer) getInjectorComponent().timerImplementation(); } @Test @@ -219,12 +218,12 @@ public void testSimpleTimeThresholding() { assertFalse(manager.isOnTarget()); // advance time a little bit, but not the full second, so should still be off target - mockTimer.setTimeInSeconds(.75); + SimHooks.stepTiming(0.75); manager.calculate(100, 100); assertFalse(manager.isOnTarget()); // advance time past the 1 second mark, so should finally report on target. - mockTimer.setTimeInSeconds(1.1); + SimHooks.stepTiming(0.35); manager.calculate(100, 100); assertTrue(manager.isOnTarget()); } @@ -240,7 +239,7 @@ public void testTimeThresholdOnTargetThenOffTargetThenOnTarget() { // Get within error threshold, and for some time manager.calculate(100, 100); assertEquals(OffTargetReason.NotTimeStable, manager.getOffTargetReason()); - mockTimer.setTimeInSeconds(1.5); + SimHooks.stepTiming(1.5); manager.calculate(100, 100); assertTrue(manager.isOnTarget()); assertEquals(OffTargetReason.OnTarget, manager.getOffTargetReason()); @@ -256,7 +255,7 @@ public void testTimeThresholdOnTargetThenOffTargetThenOnTarget() { assertEquals(OffTargetReason.NotTimeStable, manager.getOffTargetReason()); // then wait a bit - mockTimer.setTimeInSeconds(3.0); + SimHooks.stepTiming(1.5); manager.calculate(100, 100); assertTrue(manager.isOnTarget()); assertEquals(OffTargetReason.OnTarget, manager.getOffTargetReason()); diff --git a/src/test/java/xbot/common/subsystems/drive/HeadingAssistModuleTest.java b/src/test/java/xbot/common/subsystems/drive/HeadingAssistModuleTest.java index 673ca5b68..760424822 100644 --- a/src/test/java/xbot/common/subsystems/drive/HeadingAssistModuleTest.java +++ b/src/test/java/xbot/common/subsystems/drive/HeadingAssistModuleTest.java @@ -4,10 +4,10 @@ import org.junit.jupiter.api.Test; import org.wpilib.hardware.bus.CANPort; +import org.wpilib.simulation.SimHooks; import xbot.common.controls.actuators.XCANMotorController; import xbot.common.controls.sensors.mock_adapters.MockGyro; -import xbot.common.controls.sensors.mock_adapters.MockTimer; import xbot.common.injection.BaseCommonLibTest; import xbot.common.injection.electrical_contract.CANMotorControllerInfo; import xbot.common.subsystems.drive.control_logic.HeadingAssistModule; @@ -42,7 +42,7 @@ public void setUp() { ((MockBasePoseSubsystem) pose).setDriveMotors(left, right); - ((MockTimer) getInjectorComponent().timerImplementation()).advanceTimeInSecondsBy(10); + SimHooks.stepTiming(10); getInjectorComponent().dataFrameRegistry().refreshAll(); pose.periodic(); @@ -144,7 +144,7 @@ private void step2_humanStops() { private void step3_timePasses() { // time passes, this should "set" the desired angle - timer.advanceTimeInSecondsBy(1); + SimHooks.stepTiming(1); double power = ham.calculateHeadingPower(0); assertEquals(0, power, 0.001); } diff --git a/src/test/java/xbot/common/subsystems/drive/HeadingModuleTest.java b/src/test/java/xbot/common/subsystems/drive/HeadingModuleTest.java index 9793a2258..e13069863 100644 --- a/src/test/java/xbot/common/subsystems/drive/HeadingModuleTest.java +++ b/src/test/java/xbot/common/subsystems/drive/HeadingModuleTest.java @@ -4,10 +4,10 @@ import org.junit.jupiter.api.Test; import org.wpilib.hardware.bus.CANPort; +import org.wpilib.simulation.SimHooks; import xbot.common.controls.actuators.XCANMotorController; import xbot.common.controls.sensors.mock_adapters.MockGyro; -import xbot.common.controls.sensors.mock_adapters.MockTimer; import xbot.common.injection.BaseCommonLibTest; import xbot.common.injection.electrical_contract.CANMotorControllerInfo; import xbot.common.math.PIDManager; @@ -44,7 +44,7 @@ public void setUp() { ((MockBasePoseSubsystem) pose).setDriveMotors(left, right); - ((MockTimer) getInjectorComponent().timerImplementation()).advanceTimeInSecondsBy(10); + SimHooks.stepTiming(10); pose.periodic(); } diff --git a/src/test/java/xbot/common/subsystems/drive/PurePursuitCommandTest.java b/src/test/java/xbot/common/subsystems/drive/PurePursuitCommandTest.java index 50ea46890..0a38ea407 100644 --- a/src/test/java/xbot/common/subsystems/drive/PurePursuitCommandTest.java +++ b/src/test/java/xbot/common/subsystems/drive/PurePursuitCommandTest.java @@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test; import org.wpilib.math.geometry.Rotation2d; +import org.wpilib.simulation.SimHooks; import xbot.common.injection.BaseCommonLibTest; import xbot.common.math.FieldPose; @@ -35,7 +36,7 @@ public void setUp() { pose.setDriveMotors(drive.leftTank, drive.rightTank); - timer.advanceTimeInSecondsBy(10); + SimHooks.stepTiming(10); pose.periodic(); pose.setCurrentHeading(90); diff --git a/src/test/java/xbot/common/subsystems/feedback/RumbleManagerTest.java b/src/test/java/xbot/common/subsystems/feedback/RumbleManagerTest.java index fd0b3a19e..886b79f26 100644 --- a/src/test/java/xbot/common/subsystems/feedback/RumbleManagerTest.java +++ b/src/test/java/xbot/common/subsystems/feedback/RumbleManagerTest.java @@ -3,8 +3,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.wpilib.simulation.SimHooks; + import xbot.common.controls.sensors.mock_adapters.MockGamepad; -import xbot.common.controls.sensors.mock_adapters.MockTimer; import xbot.common.injection.BaseCommonLibTest; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -17,7 +18,6 @@ public class RumbleManagerTest extends BaseCommonLibTest { MockGamepad gamepad; RumbleManager rumbleManager; - MockTimer timer; @BeforeEach @Override @@ -26,7 +26,6 @@ public void setUp() { this.gamepad = (MockGamepad) getInjectorComponent().gamepadFactory().create(0); this.rumbleManager = new RumbleManager(this.gamepad); - this.timer = (MockTimer) getInjectorComponent().timerImplementation(); } @Test @@ -46,7 +45,7 @@ public void testRumbleGamepad() { rumbleManager.rumbleGamepad(5, rumbleDuration); assertTrue(rumbleManager.getIsRumbling()); - timer.advanceTimeInSecondsBy(rumbleDuration + 0.01); + SimHooks.stepTiming(rumbleDuration + 0.01); rumbleManager.periodic(); assertFalse(rumbleManager.getIsRumbling()); } diff --git a/src/test/java/xbot/common/subsystems/pose/BasePoseTest.java b/src/test/java/xbot/common/subsystems/pose/BasePoseTest.java index 7e636fada..a2462eac1 100644 --- a/src/test/java/xbot/common/subsystems/pose/BasePoseTest.java +++ b/src/test/java/xbot/common/subsystems/pose/BasePoseTest.java @@ -4,9 +4,9 @@ import org.junit.jupiter.api.Disabled; import org.wpilib.hardware.bus.CANPort; +import org.wpilib.simulation.SimHooks; import xbot.common.controls.actuators.XCANMotorController; -import xbot.common.controls.sensors.mock_adapters.MockTimer; import xbot.common.injection.BaseCommonLibTest; import xbot.common.injection.electrical_contract.CANMotorControllerInfo; @@ -16,11 +16,9 @@ public class BasePoseTest extends BaseCommonLibTest { protected MockBasePoseSubsystem pose; - protected MockTimer mockTimer; @BeforeEach public void setup() { - mockTimer = (MockTimer) getInjectorComponent().timerImplementation(); pose = (MockBasePoseSubsystem) getInjectorComponent().poseSubsystem(); XCANMotorController left = getInjectorComponent().motorControllerFactory() @@ -30,7 +28,7 @@ public void setup() { pose.setDriveMotors(left, right); - mockTimer.advanceTimeInSecondsBy(10); + SimHooks.stepTiming(10); pose.periodic(); } diff --git a/src/test/java/xbot/common/subsystems/pose/commands/SetRobotHeadingCommandTest.java b/src/test/java/xbot/common/subsystems/pose/commands/SetRobotHeadingCommandTest.java index d01635b1f..46d12e3a7 100644 --- a/src/test/java/xbot/common/subsystems/pose/commands/SetRobotHeadingCommandTest.java +++ b/src/test/java/xbot/common/subsystems/pose/commands/SetRobotHeadingCommandTest.java @@ -3,6 +3,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.wpilib.simulation.SimHooks; + import xbot.common.subsystems.pose.BasePoseSubsystem; import xbot.common.subsystems.pose.BasePoseTest; @@ -18,7 +20,7 @@ public void setup() { @Test public void testSetHeading() { - mockTimer.setTimeInSeconds(mockTimer.getFPGATimestamp() + 1); + SimHooks.stepTiming(1); verifyRobotHeading(BasePoseSubsystem.FACING_AWAY_FROM_DRIVERS); setHeading.setHeadingToApply(74); @@ -31,7 +33,7 @@ public void testSetHeading() { @Test public void testSetHeadingLargeValues() { - mockTimer.setTimeInSeconds(2); + SimHooks.stepTiming(2); verifyRobotHeading(BasePoseSubsystem.FACING_AWAY_FROM_DRIVERS); setHeading.setHeadingToApply(361); diff --git a/src/test/java/xbot/common/trajectory/SimpleTimeInterpolatorTest.java b/src/test/java/xbot/common/trajectory/SimpleTimeInterpolatorTest.java index 1f6f32f1e..cf10aa8f0 100644 --- a/src/test/java/xbot/common/trajectory/SimpleTimeInterpolatorTest.java +++ b/src/test/java/xbot/common/trajectory/SimpleTimeInterpolatorTest.java @@ -8,6 +8,7 @@ import org.wpilib.math.geometry.Rotation2d; import org.wpilib.math.geometry.Translation2d; +import org.wpilib.simulation.SimHooks; import xbot.common.injection.BaseCommonLibTest; import xbot.common.subsystems.drive.SwervePointKinematics; @@ -144,7 +145,7 @@ public void testSinglePointPartialTimeAdvance() { interpolator.calculateTarget(new Translation2d(0, 0)); - timer.advanceTimeInSecondsBy(3); + SimHooks.stepTiming(3); SimpleTimeInterpolator.InterpolationResult result = interpolator.calculateTarget(new Translation2d(0, 0)); assertEquals(0.3, result.lerpFraction, 0.01); assertEquals(new Translation2d(3, 0), result.chasePoint); @@ -162,7 +163,7 @@ public void testSinglePointFullTimeAdvanceReachesTarget() { interpolator.calculateTarget(new Translation2d(0, 0)); - timer.advanceTimeInSecondsBy(10); + SimHooks.stepTiming(10); SimpleTimeInterpolator.InterpolationResult result = interpolator.calculateTarget(new Translation2d(9, 0)); assertEquals(1.0, result.lerpFraction, 0.001); assertEquals(new Translation2d(10, 0), result.chasePoint); @@ -182,13 +183,13 @@ public void testMultipleKeyPointsAdvanceThroughSegments() { interpolator.calculateTarget(new Translation2d(0, 0)); - timer.advanceTimeInSecondsBy(3); + SimHooks.stepTiming(3); SimpleTimeInterpolator.InterpolationResult result = interpolator.calculateTarget(new Translation2d(2, 0)); assertEquals(0.6, result.lerpFraction, 0.01); assertEquals(new Translation2d(6, 0), result.chasePoint); assertFalse(result.isOnFinalPoint, "Should not be on final point yet"); - timer.advanceTimeInSecondsBy(3); + SimHooks.stepTiming(3); result = interpolator.calculateTarget(new Translation2d(7, 0)); assertEquals(0.2, result.lerpFraction, 0.01); assertEquals(new Translation2d(12, 0), result.chasePoint); @@ -209,7 +210,7 @@ public void testChasePointDistanceClamping() { // First call triggers the clamp; a second call at the same timestamp // observes the rewound time (including the now-correct lerpFraction). - timer.advanceTimeInSecondsBy(5); + SimHooks.stepTiming(5); interpolator.calculateTarget(new Translation2d(0, 0)); SimpleTimeInterpolator.InterpolationResult result = interpolator.calculateTarget(new Translation2d(0, 0)); @@ -227,7 +228,7 @@ public void testChasePointDistanceNoClampingWhenClose() { interpolator.calculateTarget(new Translation2d(0, 0)); - timer.advanceTimeInSecondsBy(3); + SimHooks.stepTiming(3); SimpleTimeInterpolator.InterpolationResult result = interpolator.calculateTarget(new Translation2d(2, 0)); assertEquals(0.3, result.lerpFraction, 0.01); } @@ -257,7 +258,7 @@ public void testPlannedVectorInDurationMode() { interpolator.calculateTarget(new Translation2d(0, 0)); - timer.advanceTimeInSecondsBy(2); + SimHooks.stepTiming(2); SimpleTimeInterpolator.InterpolationResult result = interpolator.calculateTarget(new Translation2d(1, 0)); assertEquals(2.0, result.plannedVector.getX(), 0.001); assertEquals(0.0, result.plannedVector.getY(), 0.001); @@ -275,7 +276,7 @@ public void testRotation2dIsPassedThrough() { interpolator.calculateTarget(new Translation2d(0, 0)); - timer.advanceTimeInSecondsBy(5); + SimHooks.stepTiming(5); SimpleTimeInterpolator.InterpolationResult result = interpolator.calculateTarget(new Translation2d(5, 0)); assertEquals(expectedRotation.getDegrees(), result.chaseHeading.getDegrees(), 0.001); } @@ -292,12 +293,12 @@ public void testMultipleKeyPointsOnlyAdvancesWhenTimeExceedsSegment() { interpolator.calculateTarget(new Translation2d(0, 0)); - timer.advanceTimeInSecondsBy(5); + SimHooks.stepTiming(5); SimpleTimeInterpolator.InterpolationResult result = interpolator.calculateTarget(new Translation2d(9, 0)); assertEquals(0.0, result.lerpFraction, 0.01, "Should be at start of second segment"); assertTrue(result.isOnFinalLeg, "Should be on final leg"); - timer.advanceTimeInSecondsBy(5); + SimHooks.stepTiming(5); result = interpolator.calculateTarget(new Translation2d(9, 0)); assertEquals(1.0, result.lerpFraction, 0.001, "Should be at end of second segment"); assertTrue(result.isOnFinalPoint, "Should be on final point"); @@ -318,7 +319,7 @@ public void testZeroTimeSegmentSkipAdvancesToNext() { interpolator.calculateTarget(new Translation2d(0, 0)); - timer.advanceTimeInSecondsBy(5); + SimHooks.stepTiming(5); SimpleTimeInterpolator.InterpolationResult result = interpolator.calculateTarget(new Translation2d(5, 0)); assertEquals(2, interpolator.index, "Should have advanced past zero-time segment"); assertEquals(0.0, result.lerpFraction, 0.01, "LerpFraction should be 0 on third segment");