55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
|
#!/usr/bin/env python3
|
||
|
import argparse
|
||
|
import typing as t
|
||
|
import time
|
||
|
from pathlib import Path
|
||
|
|
||
|
import serial
|
||
|
|
||
|
|
||
|
def iter_frames(raw_data: bytes) -> t.Iterator[bytes]:
|
||
|
FRAME_START = 0x02
|
||
|
next_frame = b""
|
||
|
# Discard first bytes
|
||
|
raw_data = raw_data[raw_data.find(FRAME_START) :]
|
||
|
|
||
|
for ch in raw_data:
|
||
|
# Discard first bytes
|
||
|
if ch == FRAME_START and next_frame:
|
||
|
yield next_frame
|
||
|
next_frame = b""
|
||
|
next_frame += bytes([ch])
|
||
|
|
||
|
|
||
|
def main():
|
||
|
parser = argparse.ArgumentParser()
|
||
|
parser.add_argument("-p", "--port", default="/dev/ttyUSB1")
|
||
|
parser.add_argument("-b", "--baud", type=int, default=1200)
|
||
|
parser.add_argument(
|
||
|
"--frame-gap", type=int, default=1500, help="Time between two frames (in ms)"
|
||
|
)
|
||
|
parser.add_argument(
|
||
|
"recorded_data",
|
||
|
help="File containing real recorded data to replay",
|
||
|
type=Path,
|
||
|
)
|
||
|
args = parser.parse_args()
|
||
|
|
||
|
data: bytes = b""
|
||
|
with args.recorded_data.open("rb") as h:
|
||
|
data = h.read()
|
||
|
|
||
|
with serial.Serial(port=args.port, baudrate=args.baud) as ser:
|
||
|
for frame in iter_frames(data):
|
||
|
print(f"Feeding {len(frame)}b frame")
|
||
|
start_time = time.monotonic()
|
||
|
ser.write(frame)
|
||
|
elapsed_time = time.monotonic() - start_time
|
||
|
sleep_time = args.frame_gap / 1000 - elapsed_time
|
||
|
if sleep_time > 0:
|
||
|
time.sleep(sleep_time)
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|