blob: a2e4e13eda0422547cf4526834f58298f49c3ed3 [file] [log] [blame]
Austin Schuh812d0d12021-11-04 20:16:48 -07001// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#include "frc/TimesliceRobot.h" // NOLINT(build/include_order)
6
7#include <stdint.h>
8
9#include <atomic>
10#include <thread>
11
12#include "frc/simulation/DriverStationSim.h"
13#include "frc/simulation/SimHooks.h"
14#include "gtest/gtest.h"
15
16using namespace frc;
17
18namespace {
19class TimesliceRobotTest : public ::testing::Test {
20 protected:
21 void SetUp() override { frc::sim::PauseTiming(); }
22
23 void TearDown() override { frc::sim::ResumeTiming(); }
24};
25
26class MockRobot : public TimesliceRobot {
27 public:
28 std::atomic<uint32_t> m_robotPeriodicCount{0};
29
30 MockRobot() : TimesliceRobot{2_ms, 5_ms} {}
31
32 void RobotPeriodic() override { m_robotPeriodicCount++; }
33};
34} // namespace
35
36TEST_F(TimesliceRobotTest, Schedule) {
37 MockRobot robot;
38
39 std::atomic<uint32_t> callbackCount1{0};
40 std::atomic<uint32_t> callbackCount2{0};
41
42 // Timeslice allocation table
43 //
44 // | Name | Offset (ms) | Allocation (ms)|
45 // |-----------------|-------------|----------------|
46 // | RobotPeriodic() | 0 | 2 |
47 // | Callback 1 | 2 | 0.5 |
48 // | Callback 2 | 2.5 | 1 |
49 robot.Schedule([&] { callbackCount1++; }, 0.5_ms);
50 robot.Schedule([&] { callbackCount2++; }, 1_ms);
51
52 std::thread robotThread{[&] { robot.StartCompetition(); }};
53
54 frc::sim::DriverStationSim::SetEnabled(false);
55 frc::sim::DriverStationSim::NotifyNewData();
56 frc::sim::StepTiming(0_ms); // Wait for Notifiers
57
58 // Functions scheduled with addPeriodic() are delayed by one period before
59 // their first run (5 ms for this test's callbacks here and 20 ms for
60 // robotPeriodic()).
61 frc::sim::StepTiming(5_ms);
62
63 EXPECT_EQ(0u, robot.m_robotPeriodicCount);
64 EXPECT_EQ(0u, callbackCount1);
65 EXPECT_EQ(0u, callbackCount2);
66
67 // Step to 1.5 ms
68 frc::sim::StepTiming(1.5_ms);
69 EXPECT_EQ(0u, robot.m_robotPeriodicCount);
70 EXPECT_EQ(0u, callbackCount1);
71 EXPECT_EQ(0u, callbackCount2);
72
73 // Step to 2.25 ms
74 frc::sim::StepTiming(0.75_ms);
75 EXPECT_EQ(0u, robot.m_robotPeriodicCount);
76 EXPECT_EQ(1u, callbackCount1);
77 EXPECT_EQ(0u, callbackCount2);
78
79 // Step to 2.75 ms
80 frc::sim::StepTiming(0.5_ms);
81 EXPECT_EQ(0u, robot.m_robotPeriodicCount);
82 EXPECT_EQ(1u, callbackCount1);
83 EXPECT_EQ(1u, callbackCount2);
84
85 robot.EndCompetition();
86 robotThread.join();
87}
88
89TEST_F(TimesliceRobotTest, ScheduleOverrun) {
90 MockRobot robot;
91
92 robot.Schedule([] {}, 0.5_ms);
93 robot.Schedule([] {}, 1_ms);
94
95 // offset = 2 ms + 0.5 ms + 1 ms = 3.5 ms
96 // 3.5 ms + 3 ms allocation = 6.5 ms > max of 5 ms
97 EXPECT_THROW(robot.Schedule([] {}, 3_ms), std::runtime_error);
98
99 robot.EndCompetition();
100}