forked from Team254/FRC-2019-Public
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Looper.java
93 lines (77 loc) · 2.57 KB
/
Looper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.team254.frc2019.loops;
import com.team254.frc2019.Constants;
import com.team254.lib.util.CrashTrackingRunnable;
import edu.wpi.first.wpilibj.Notifier;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import java.util.ArrayList;
import java.util.List;
/**
* This code runs all of the robot's loops. Loop objects are stored in a List object. They are started when the robot
* powers up and stopped after the match.
*/
public class Looper implements ILooper {
public final double kPeriod = Constants.kLooperDt;
private boolean mRunning;
private final Notifier mNotifier;
private final List<Loop> mLoops;
private final Object mTaskRunningLock = new Object();
private double mTimestamp = 0;
private double mDT = 0;
private final CrashTrackingRunnable runnable_ = new CrashTrackingRunnable() {
@Override
public void runCrashTracked() {
synchronized (mTaskRunningLock) {
if (mRunning) {
double now = Timer.getFPGATimestamp();
for (Loop loop : mLoops) {
loop.onLoop(now);
}
mDT = now - mTimestamp;
mTimestamp = now;
}
}
}
};
public Looper() {
mNotifier = new Notifier(runnable_);
mRunning = false;
mLoops = new ArrayList<>();
}
@Override
public synchronized void register(Loop loop) {
synchronized (mTaskRunningLock) {
mLoops.add(loop);
}
}
public synchronized void start() {
if (!mRunning) {
System.out.println("Starting loops");
synchronized (mTaskRunningLock) {
mTimestamp = Timer.getFPGATimestamp();
for (Loop loop : mLoops) {
loop.onStart(mTimestamp);
}
mRunning = true;
}
mNotifier.startPeriodic(kPeriod);
}
}
public synchronized void stop() {
if (mRunning) {
System.out.println("Stopping loops");
mNotifier.stop();
synchronized (mTaskRunningLock) {
mRunning = false;
mTimestamp = Timer.getFPGATimestamp();
for (Loop loop : mLoops) {
System.out.println("Stopping " + loop);
loop.onStop(mTimestamp);
}
}
}
}
public void outputToSmartDashboard() {
SmartDashboard.putNumber("looper_dt", mDT);
}
}