Skip to content

Commit c7e1969

Browse files
committed
Add support for expiring values
1 parent 62ee197 commit c7e1969

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/sensesp/system/expiring_value.h

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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_

0 commit comments

Comments
 (0)