File size: 1,523 Bytes
bd16e4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Record the sim duck's exact state from the body server (op "read" on :7801) at N Hz into a jsonl.

Read-only: "read" returns trunk position, quaternion, joint positions (wire order) and sim time,
and mutates nothing. No hello (the body server does not require it for reads). Stops on SIGTERM
or after --max-s seconds.
usage: duck-state-rec.py <out.jsonl> [--hz 30] [--max-s 180] [--port 7801]
"""
import argparse, json, signal, socket, sys, time

ap = argparse.ArgumentParser()
ap.add_argument("out")
ap.add_argument("--hz", type=float, default=30.0)
ap.add_argument("--max-s", type=float, default=180.0)
ap.add_argument("--port", type=int, default=7801)
a = ap.parse_args()

stop = False
def _term(*_):
    global stop
    stop = True
signal.signal(signal.SIGTERM, _term)
signal.signal(signal.SIGINT, _term)

s = socket.create_connection(("127.0.0.1", a.port), timeout=2)
f = s.makefile("rw")
period = 1.0 / a.hz
t0 = time.time()
nxt = t0
n = 0
with open(a.out, "w") as out:
    while not stop and time.time() - t0 < a.max_s:
        f.write('{"op":"read"}\n'); f.flush()
        r = json.loads(f.readline())
        out.write(json.dumps({"wall": time.time(), "sim_time": r.get("sim_time"), "trunk": r.get("trunk"),
                              "quat": r["imu"]["quat"], "positions": r["positions"]}) + "\n")
        n += 1
        nxt += period
        d = nxt - time.time()
        if d > 0:
            time.sleep(d)
print(f"recorded {n} frames in {time.time() - t0:.1f} s", file=sys.stderr)