RaidZeroLib
Coroutine robot framework for VEX V5
Loading...
Searching...
No Matches
Sensor.hpp
1#pragma once
2#include <cstdint>
3#include <limits>
4#include <optional>
5
6#include "RaidZeroLib/api/Runtime/Runtime.hpp"
7
8namespace rz {
9
24template <class T>
25class Sensor {
26 public:
27 Sensor() = default;
28 Sensor(const Sensor&) = delete;
29 Sensor& operator=(const Sensor&) = delete;
30 Sensor(Sensor&&) = delete;
31 Sensor& operator=(Sensor&&) = delete;
32 virtual ~Sensor() = default;
33
35 [[nodiscard]] T get() {
36 sync();
37 return raw() + continuity;
38 }
39
41 [[nodiscard]] T delta() {
42 sync();
43 return lastDelta;
44 }
45
46 [[nodiscard]] virtual bool connected() const = 0;
47
48 protected:
51 [[nodiscard]] virtual T raw() const = 0;
52
54 [[nodiscard]] virtual std::uint32_t epoch() const { return 0; }
55
56 private:
57 // Takes this tick's snapshot, once, on the first get() or delta() of the tick.
58 void sync() {
59 const std::uint64_t tick = Runtime::globalTickId();
60 if (tick == syncedTick) {
61 return;
62 }
63 syncedTick = tick;
64
65 if (!connected()) {
66 lastDelta = T{};
67 return;
68 }
69
70 const T current = raw();
71 const std::uint32_t currentEpoch = epoch();
72 if (baseline && currentEpoch != baselineEpoch) {
73 continuity += *baseline - current; // the reading restarted: keep get() where it was
74 }
75 lastDelta = (baseline && currentEpoch == baselineEpoch) ? current - *baseline : T{};
76 baseline = current;
77 baselineEpoch = currentEpoch;
78 }
79
80 T continuity{}; // absorbs restarts after a power cycle; never set by consumers
81 std::optional<T> baseline;
82 std::uint32_t baselineEpoch = 0;
83 std::uint64_t syncedTick = std::numeric_limits<std::uint64_t>::max();
84 T lastDelta{};
85};
86
87} // namespace rz
static std::uint64_t globalTickId() noexcept
Identifies the current tick uniquely across every runtime there has been; never repeats....
Definition Runtime.hpp:132
virtual T raw() const =0
This tick's reading from the source; the last good value while disconnected. May restart after a reco...
Sensor(Sensor &&)=delete
T get()
The current reading. The last good value while disconnected.
Definition Sensor.hpp:35
Sensor()=default
Sensor & operator=(const Sensor &)=delete
Sensor(const Sensor &)=delete
Sensor & operator=(Sensor &&)=delete
virtual std::uint32_t epoch() const
Increments every time the source reconnects. Readings across a reconnect are not comparable.
Definition Sensor.hpp:54
virtual ~Sensor()=default
T delta()
Change since the previous snapshot (covers several ticks if nobody read in between).
Definition Sensor.hpp:41
virtual bool connected() const =0
Definition DriverControl.hpp:11