-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoorstate.py
105 lines (85 loc) · 3.04 KB
/
doorstate.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
from struct import pack, unpack, calcsize
from multiprocessing.shared_memory import SharedMemory
from time import time
class DoorState:
STRUCT_FMT: str = 'diddii'
STRUCT_SIZE: int = calcsize(STRUCT_FMT)
def __init__(self):
self._process_start_time: float = time()
self._door_is_open: int = -1
self._door_open_time: float = -1
self._door_close_time: float = -1
self._num_authorized: int = 0
self._num_unauthorized: int = 0
@property
def process_uptime_seconds(self) -> float:
return time() - self._process_start_time
@property
def door_open_seconds(self) -> float:
if self._door_is_open == 1:
return self.seconds_since_opened
return 0
@property
def door_is_open(self) -> int:
return self._door_is_open
@property
def seconds_since_opened(self) -> float:
if self._door_open_time == -1:
return -1
return time() - self._door_open_time
@property
def seconds_since_closed(self) -> float:
if self._door_close_time == -1:
return -1
return time() - self._door_close_time
@property
def unauthorized_scans(self) -> int:
return self._num_unauthorized
@property
def authorized_scans(self) -> int:
return self._num_authorized
def set_door_open(self, shm: SharedMemory):
self._door_is_open = 1
self._door_open_time = time()
self.write_to_shm(shm)
def set_door_closed(self, shm: SharedMemory):
self._door_is_open = 0
self._door_close_time = time()
self.write_to_shm(shm)
def set_scan_authorized(self, shm: SharedMemory):
self._num_authorized += 1
self.write_to_shm(shm)
def set_scan_unauthorized(self, shm: SharedMemory):
self._num_unauthorized += 1
self.write_to_shm(shm)
@property
def _value(self) -> list:
return [
self._process_start_time,
self._door_is_open,
self._door_open_time,
self._door_close_time,
self._num_authorized,
self._num_unauthorized
]
def __repr__(self) -> str:
return f'<DoorState(' \
f'process_start_time={self._process_start_time}, ' \
f'door_is_open={self._door_is_open}, ' \
f'door_open_time={self._door_open_time}, ' \
f'door_close_time={self._door_close_time}, ' \
f'num_authorized={self._num_authorized}, ' \
f'num_unauthorized={self._num_unauthorized})>'
def write_to_shm(self, shm: SharedMemory):
shm.buf[:] = pack(self.STRUCT_FMT, *self._value)
@classmethod
def from_shm_buffer(cls, shm: SharedMemory) -> 'DoorState':
vals = unpack(DoorState.STRUCT_FMT, shm.buf)
c = DoorState()
c._process_start_time = vals[0]
c._door_is_open = vals[1]
c._door_open_time = vals[2]
c._door_close_time = vals[3]
c._num_authorized = vals[4]
c._num_unauthorized = vals[5]
return c