RaidZeroLib
Coroutine robot framework for VEX V5
Loading...
Searching...
No Matches
Watchdog.hpp
1#pragma once
2#include <atomic>
3#include <cstdint>
4#include <optional>
5#include <source_location>
6
7#include "RaidZeroLib/api/Units/Units.hpp"
8
9namespace rz {
10
18class Watchdog {
19 public:
20 explicit Watchdog(Duration timeout) : timeout(timeout) {}
21
22 Watchdog(const Watchdog&) = delete;
23 Watchdog& operator=(const Watchdog&) = delete;
24
26 void tickStarted() noexcept { heartbeat.fetch_add(1, std::memory_order_relaxed); }
27
29 void resuming(std::source_location location) noexcept { lastResumed_.store(location, std::memory_order_relaxed); }
30
32 [[nodiscard]] bool stalled(Time now) {
33 const std::uint32_t beat = heartbeat.load(std::memory_order_relaxed);
34 if (timeout <= Duration{} || beat == 0) {
35 return false;
36 }
37 if (beat != lastSeen) {
38 lastSeen = beat;
39 lastChange = now;
40 return false;
41 }
42 return now - lastChange >= timeout;
43 }
44
46 [[nodiscard]] std::source_location lastResumed() const noexcept {
47 return lastResumed_.load(std::memory_order_relaxed);
48 }
49
50 private:
51 // Shared between the runtime's task (writes) and the watching task (reads).
52 std::atomic<std::uint32_t> heartbeat{0};
53 std::atomic<std::source_location> lastResumed_{};
54 static_assert(std::atomic<std::source_location>::is_always_lock_free);
55
56 // Used only by the watching task.
57 Duration timeout;
58 std::optional<std::uint32_t> lastSeen;
59 Time lastChange{};
60};
61
62} // namespace rz
Watchdog & operator=(const Watchdog &)=delete
void resuming(std::source_location location) noexcept
Called by the runtime just before it resumes a coroutine that was waiting at location.
Definition Watchdog.hpp:29
void tickStarted() noexcept
Called by the runtime at the start of every tick.
Definition Watchdog.hpp:26
bool stalled(Time now)
Polled from the watching task: true once no tick has started for timeout.
Definition Watchdog.hpp:32
Watchdog(Duration timeout)
Definition Watchdog.hpp:20
Watchdog(const Watchdog &)=delete
std::source_location lastResumed() const noexcept
Where the coroutine most recently resumed was waiting: the code after it is what's blocking.
Definition Watchdog.hpp:46
Time now()
Time at the start of the current tick of the current runtime.
Definition Runtime.hpp:209
au::QuantityD< au::Seconds > Duration
Definition Units.hpp:16
au::QuantityPointD< au::Seconds > Time
Definition Units.hpp:17
Definition DriverControl.hpp:11