-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatalogger.py
More file actions
36 lines (27 loc) · 959 Bytes
/
datalogger.py
File metadata and controls
36 lines (27 loc) · 959 Bytes
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
from time import time
import json
class DataLogger:
def __init__(self, columns):
self.timestamps = []
self.columns = columns
self.data = {c: [] for c in columns}
self.timestamps = {c: [] for c in columns}
def log(self, value, column, timestamp=None):
if timestamp is None:
timestamp = time()
timestamps = self.timestamps[column]
data = self.data[column]
# append new data
data.append(value)
timestamps.append(timestamp)
def get_last_n_seconds(self, n, column):
now = time()
data = self.data[column]
timestamps = self.timestamps[column]
i = len(data)
while i >= 1 and now - timestamps[i - 1] < n:
i = i - 1
return data[i:], timestamps[i:]
def save(self, path):
with open(path, 'w') as f:
json.dump({'data': self.data, 'timestamps': self.timestamps}, f, indent=2)