-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarystate.py
57 lines (47 loc) · 1.52 KB
/
binarystate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
generic binary state tracking class
"""
import time
import adafruit_logging as logging
class BinaryState:
"""
provides state tracking based on updating value periodically
The state duration is stored as float in order to allow for sub-second updates.
This in turn can lead to lose of precision over time.
"""
def __init__(
self,
):
"""
set the initial state
"""
self.prev_state = None
self.state_duration = 0
self.stamp = time.monotonic_ns() # use _ns() to avoid losing precision
def update(self, cur_state) -> float:
"""
:param cur_state: current state
:return: duration of the state in seconds
"""
logger = logging.getLogger(__name__)
# Record the duration of table position.
if self.prev_state is not None:
if self.prev_state == cur_state:
self.state_duration += (
time.monotonic_ns() - self.stamp
) / 1_000_000_000
logger.debug(
f"state '{cur_state}' preserved (for {self.state_duration} sec)"
)
else:
logger.debug(f"state changed {self.prev_state} -> {cur_state}")
self.state_duration = 0
self.prev_state = cur_state
self.stamp = time.monotonic_ns()
return self.state_duration
def reset(self):
"""
reset the state
"""
self.prev_state = None
self.state_duration = 0