26public class Watchdog implements Closeable, Comparable<Watchdog> {
28 private static final long MIN_PRINT_PERIOD = 1_000_000_000L;
32 private long m_startTime;
33 private double m_timeout;
34 private long m_expirationTime;
35 private final Runnable m_callback;
36 private long m_lastTimeoutPrint;
40 boolean m_suppressTimeoutMessage;
42 private final Tracer m_tracer;
44 private static final PriorityQueue<Watchdog> m_watchdogs =
new PriorityQueue<>();
45 private static ReentrantLock m_queueMutex =
new ReentrantLock();
46 private static int m_notifier;
50 NotifierJNI.setNotifierName(m_notifier,
"Watchdog");
51 startDaemonThread(Watchdog::schedulerFunc);
60 public Watchdog(
double timeout, Runnable callback) {
62 m_callback = callback;
72 public Watchdog(Time timeout, Runnable callback) {
73 this(timeout.in(Seconds), callback);
82 public boolean equals(Object obj) {
83 return obj instanceof
Watchdog watchdog && m_expirationTime == watchdog.m_expirationTime;
87 public int hashCode() {
88 return Long.hashCode(m_expirationTime);
95 return Long.compare(m_expirationTime, rhs.m_expirationTime);
104 return (
HALUtil.getMonotonicTime() - m_startTime) / 1e9;
113 m_startTime =
HALUtil.getMonotonicTime();
114 m_tracer.clearEpochs();
121 m_watchdogs.remove(
this);
122 m_expirationTime = m_startTime + Math.round(m_timeout * 1e9);
123 m_watchdogs.add(
this);
126 m_queueMutex.unlock();
140 m_queueMutex.unlock();
154 m_queueMutex.unlock();
165 m_tracer.addEpoch(epochName);
174 m_tracer.printEpochs();
188 m_startTime =
HALUtil.getMonotonicTime();
189 m_tracer.clearEpochs();
195 m_watchdogs.remove(
this);
196 m_expirationTime = m_startTime + Math.round(m_timeout * 1e9);
197 m_watchdogs.add(
this);
200 m_queueMutex.unlock();
208 m_watchdogs.remove(
this);
211 m_queueMutex.unlock();
223 m_suppressTimeoutMessage = suppress;
226 @SuppressWarnings(
"resource")
227 private static
void updateAlarm() {
228 if (m_watchdogs.isEmpty()) {
229 NotifierJNI.cancelNotifierAlarm(m_notifier, true);
231 NotifierJNI.setNotifierAlarm(m_notifier, m_watchdogs.peek().m_expirationTime, 0, true, true);
235 private static Thread startDaemonThread(Runnable target) {
236 Thread inst =
new Thread(target);
237 inst.setDaemon(
true);
242 private static void schedulerFunc() {
243 while (!Thread.currentThread().isInterrupted()) {
245 WPIUtilJNI.waitForObject(m_notifier);
246 }
catch (InterruptedException ex) {
247 Thread.currentThread().interrupt();
250 long curTime = HALUtil.getMonotonicTime();
254 if (m_watchdogs.isEmpty()) {
260 Watchdog watchdog = m_watchdogs.poll();
262 if (curTime - watchdog.m_lastTimeoutPrint > MIN_PRINT_PERIOD) {
263 watchdog.m_lastTimeoutPrint = curTime;
264 if (!watchdog.m_suppressTimeoutMessage) {
265 DriverStationErrors.reportWarning(
266 String.format(
"Watchdog not fed within %.6fs\n", watchdog.m_timeout),
false);
273 watchdog.m_isExpired =
true;
275 m_queueMutex.unlock();
277 watchdog.m_callback.run();
284 m_queueMutex.unlock();