Skip to content

Commit 8d9db59

Browse files
committed
har_trees: Fix missing header in recorded .npy files
Also add a basic test
1 parent 3a4b097 commit 8d9db59

File tree

2 files changed

+45
-6
lines changed

2 files changed

+45
-6
lines changed

examples/har_trees/recorder.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11

22
import npyfile
33

4-
# mpremote mip install "github:peterhinch/micropython-async/v3/primitives"
5-
from primitives import Pushbutton
6-
74
import asyncio
85
import os
96
import time
@@ -13,7 +10,8 @@
1310

1411

1512
def format_time(secs):
16-
year, month, day, hour, minute, second, _, _ = time.gmtime(secs)
13+
tt = time.gmtime(secs)
14+
year, month, day, hour, minute, second, _, _ = tt[0:8]
1715
formatted = f'{year:04d}-{month:02d}-{day:02d}T{hour:02d}:{minute:02d}:{second:02d}'
1816
return formatted
1917

@@ -68,13 +66,15 @@ def process(self, data):
6866
out_path = f'{self._directory}/{time_str}_{self._classname}{self._suffix}'
6967
out_typecode = 'h'
7068
out_shape = (3, self._recording_samples)
71-
self._recording_file = npyfile.Writer(open(out_path, 'w'), out_shape, out_typecode)
69+
self._recording_file_path = out_path
70+
self._recording_file = npyfile.Writer(open(out_path, 'wb'), out_shape, out_typecode)
71+
self._recording_file._write_header()
7272
print(f'record-file-open t={t:.3f} file={out_path}')
7373

7474
# TODO: avoid writing too much at end of file
7575
self._recording_file.write_values(data)
7676
print(f'recorder-write-chunk t={t:.3f}')
77-
if self._recording_file.written_bytes > 3*2*self._recording_samples:
77+
if self._recording_file.written_bytes >= 3*2*self._recording_samples:
7878
# rotate file
7979
self.close()
8080
print(f'record-file-rotate t={t:.3f}')

examples/har_trees/test_recorder.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2+
import array
3+
import math
4+
5+
import npyfile
6+
7+
print(npyfile.__file__)
8+
9+
from recorder import Recorder
10+
11+
samplerate = 100
12+
chunk_length = 30
13+
file_duration = 2.0
14+
test_data_dir = 'test_har_record'
15+
16+
def check_file(path):
17+
shape, data = npyfile.load(path)
18+
return shape
19+
20+
def test_recorder_one_file():
21+
22+
decoded = array.array('h', (0 for _ in range(3*chunk_length)))
23+
24+
n_chunks = math.ceil((file_duration * samplerate) / chunk_length)
25+
26+
with Recorder(samplerate, file_duration, directory=test_data_dir) as recorder:
27+
recorder.start()
28+
29+
for i in range(n_chunks):
30+
recorder.process(decoded)
31+
32+
p = recorder._recording_file_path
33+
34+
shape = check_file(p)
35+
assert shape[0] == 3
36+
assert shape[1] == int(file_duration*samplerate)
37+
38+
if __name__ == '__main__':
39+
test_recorder_one_file()

0 commit comments

Comments
 (0)