[wpilib] Support scheduling functions more often than robot loop (#2766)

Currently, teams have to make a Notifier to run feedback controllers
more often than the TimedRobot loop period of 20ms (running TimedRobot
more often than this is not advised). This lets users add callbacks to
the main robot loop that run at a user-defined period. This allows
running feedback controllers more often, but does so synchronously with
TimedRobot so there aren't any thread safety issues.
This commit is contained in:
Tyler Veness
2020-10-16 17:56:37 -07:00
committed by GitHub
parent 57a97e3fb3
commit 7c8f1cf7af
5 changed files with 361 additions and 32 deletions

View File

@@ -309,3 +309,86 @@ TEST_F(TimedRobotTest, Test) {
robot.EndCompetition();
robotThread.join();
}
TEST_F(TimedRobotTest, AddPeriodic) {
MockRobot robot;
std::atomic<uint32_t> callbackCount{0};
robot.AddPeriodic([&] { callbackCount++; }, 10_ms);
std::thread robotThread{[&] { robot.StartCompetition(); }};
frc::sim::DriverStationSim::SetEnabled(false);
frc::sim::DriverStationSim::NotifyNewData();
frc::sim::StepTiming(0_ms); // Wait for Notifiers
EXPECT_EQ(0u, robot.m_disabledInitCount);
EXPECT_EQ(0u, robot.m_disabledPeriodicCount);
EXPECT_EQ(0u, callbackCount);
frc::sim::StepTiming(10_ms);
EXPECT_EQ(0u, robot.m_disabledInitCount);
EXPECT_EQ(0u, robot.m_disabledPeriodicCount);
EXPECT_EQ(1u, callbackCount);
frc::sim::StepTiming(10_ms);
EXPECT_EQ(1u, robot.m_disabledInitCount);
EXPECT_EQ(1u, robot.m_disabledPeriodicCount);
EXPECT_EQ(2u, callbackCount);
robot.EndCompetition();
robotThread.join();
}
TEST_F(TimedRobotTest, AddPeriodicWithOffset) {
MockRobot robot;
std::atomic<uint32_t> callbackCount{0};
robot.AddPeriodic([&] { callbackCount++; }, 10_ms, 5_ms);
// Expirations in this test (ms)
//
// Robot | Callback
// ================
// 20 | 15
// 40 | 25
std::thread robotThread{[&] { robot.StartCompetition(); }};
frc::sim::DriverStationSim::SetEnabled(false);
frc::sim::DriverStationSim::NotifyNewData();
frc::sim::StepTiming(0_ms); // Wait for Notifiers
EXPECT_EQ(0u, robot.m_disabledInitCount);
EXPECT_EQ(0u, robot.m_disabledPeriodicCount);
EXPECT_EQ(0u, callbackCount);
frc::sim::StepTiming(7.5_ms);
EXPECT_EQ(0u, robot.m_disabledInitCount);
EXPECT_EQ(0u, robot.m_disabledPeriodicCount);
EXPECT_EQ(0u, callbackCount);
frc::sim::StepTiming(7.5_ms);
EXPECT_EQ(0u, robot.m_disabledInitCount);
EXPECT_EQ(0u, robot.m_disabledPeriodicCount);
EXPECT_EQ(1u, callbackCount);
frc::sim::StepTiming(5_ms);
EXPECT_EQ(1u, robot.m_disabledInitCount);
EXPECT_EQ(1u, robot.m_disabledPeriodicCount);
EXPECT_EQ(1u, callbackCount);
frc::sim::StepTiming(5_ms);
EXPECT_EQ(1u, robot.m_disabledInitCount);
EXPECT_EQ(1u, robot.m_disabledPeriodicCount);
EXPECT_EQ(2u, callbackCount);
robot.EndCompetition();
robotThread.join();
}