File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ #ifndef SENSESP_SRC_SENSESP_SYSTEM_EXPIRING_VALUE_H_
2
+ #define SENSESP_SRC_SENSESP_SYSTEM_EXPIRING_VALUE_H_
3
+
4
+ namespace sensesp {
5
+
6
+ /* *
7
+ * @brief Value container that keeps track of its expiration time.
8
+ *
9
+ * The value is considered expired if the time since the last update is greater
10
+ * than the expiration duration. When expired, the value is replaced with an
11
+ * expiration placeholder value.
12
+ *
13
+ * @tparam T
14
+ */
15
+ template <typename T>
16
+ class ExpiringValue {
17
+ public:
18
+ ExpiringValue ()
19
+ : value_{},
20
+ expiration_duration_{1000 },
21
+ last_update_{0 },
22
+ expired_value_{T{}} {}
23
+
24
+ ExpiringValue (T value, unsigned long expiration_duration, T expired_value)
25
+ : value_{value},
26
+ expiration_duration_{expiration_duration},
27
+ expired_value_{expired_value},
28
+ last_update_{millis ()} {}
29
+
30
+ void update (T value) {
31
+ value_ = value;
32
+ last_update_ = millis ();
33
+ }
34
+
35
+ T get () const {
36
+ if (!is_expired ()) {
37
+ return value_;
38
+ } else {
39
+ return expired_value_;
40
+ }
41
+ }
42
+
43
+ bool is_expired () const {
44
+ return millis () - last_update_ > expiration_duration_;
45
+ }
46
+
47
+ private:
48
+ T value_;
49
+ T expired_value_;
50
+ unsigned long expiration_duration_;
51
+ unsigned long last_update_;
52
+ };
53
+
54
+ } // namespace sensesp
55
+
56
+ #endif // SENSESP_SRC_SENSESP_SYSTEM_EXPIRING_VALUE_H_
You can’t perform that action at this time.
0 commit comments