4 Commits

7 changed files with 181 additions and 66 deletions

3
.gitignore vendored
View File

@ -5,4 +5,5 @@ __pycache__/
*.tmp *.tmp
*.bak *.bak
*.swp *.swp
*.swo *.swo
acm_9

Binary file not shown.

View File

@ -89,7 +89,14 @@ def run_matplotlib(args):
q: Queue[SweepPacket] = Queue(maxsize=1000) q: Queue[SweepPacket] = Queue(maxsize=1000)
stop_event = threading.Event() stop_event = threading.Event()
reader = SweepReader(args.port, args.baud, q, stop_event, fancy=bool(args.fancy)) reader = SweepReader(
args.port,
args.baud,
q,
stop_event,
fancy=bool(args.fancy),
bin_mode=bool(getattr(args, "bin_mode", False)),
)
reader.start() reader.start()
max_sweeps = int(max(10, args.max_sweeps)) max_sweeps = int(max(10, args.max_sweeps))

View File

@ -106,7 +106,14 @@ def run_pyqtgraph(args):
q: Queue[SweepPacket] = Queue(maxsize=1000) q: Queue[SweepPacket] = Queue(maxsize=1000)
stop_event = threading.Event() stop_event = threading.Event()
reader = SweepReader(args.port, args.baud, q, stop_event, fancy=bool(args.fancy)) reader = SweepReader(
args.port,
args.baud,
q,
stop_event,
fancy=bool(args.fancy),
bin_mode=bool(getattr(args, "bin_mode", False)),
)
reader.start() reader.start()
max_sweeps = int(max(10, args.max_sweeps)) max_sweeps = int(max(10, args.max_sweeps))

View File

@ -24,6 +24,7 @@ class SweepReader(threading.Thread):
out_queue: "Queue[SweepPacket]", out_queue: "Queue[SweepPacket]",
stop_event: threading.Event, stop_event: threading.Event,
fancy: bool = False, fancy: bool = False,
bin_mode: bool = False,
): ):
super().__init__(daemon=True) super().__init__(daemon=True)
self._port_path = port_path self._port_path = port_path
@ -32,11 +33,17 @@ class SweepReader(threading.Thread):
self._stop = stop_event self._stop = stop_event
self._src: Optional[SerialLineSource] = None self._src: Optional[SerialLineSource] = None
self._fancy = bool(fancy) self._fancy = bool(fancy)
self._bin_mode = bool(bin_mode)
self._max_width: int = 0 self._max_width: int = 0
self._sweep_idx: int = 0 self._sweep_idx: int = 0
self._last_sweep_ts: Optional[float] = None self._last_sweep_ts: Optional[float] = None
self._n_valid_hist = deque() self._n_valid_hist = deque()
@staticmethod
def _u32_to_i32(v: int) -> int:
"""Преобразование 32-bit слова в знаковое значение."""
return v - 0x1_0000_0000 if (v & 0x8000_0000) else v
def _finalize_current(self, xs, ys, channels: Optional[set]): def _finalize_current(self, xs, ys, channels: Optional[set]):
if not xs: if not xs:
return return
@ -135,11 +142,148 @@ class SweepReader(threading.Thread):
except Exception: except Exception:
pass pass
def run(self): def _run_ascii_stream(self, chunk_reader: SerialChunkReader):
xs: list = [] xs: list[int] = []
ys: list = [] ys: list[int] = []
cur_channel: Optional[int] = None cur_channel: Optional[int] = None
cur_channels: set = set() cur_channels: set[int] = set()
buf = bytearray()
while not self._stop.is_set():
data = chunk_reader.read_available()
if data:
buf += data
else:
time.sleep(0.0005)
continue
while True:
nl = buf.find(b"\n")
if nl == -1:
break
line = bytes(buf[:nl])
del buf[: nl + 1]
if line.endswith(b"\r"):
line = line[:-1]
if not line:
continue
if line.startswith(b"Sweep_start"):
self._finalize_current(xs, ys, cur_channels)
xs.clear()
ys.clear()
cur_channel = None
cur_channels.clear()
continue
if len(line) >= 3:
parts = line.split()
if len(parts) >= 3 and (parts[0].lower() == b"s" or parts[0].lower().startswith(b"s")):
try:
if parts[0].lower() == b"s":
if len(parts) >= 4:
ch = int(parts[1], 10)
x = int(parts[2], 10)
y = int(parts[3], 10)
else:
ch = 0
x = int(parts[1], 10)
y = int(parts[2], 10)
else:
ch = int(parts[0][1:], 10)
x = int(parts[1], 10)
y = int(parts[2], 10)
except Exception:
continue
if cur_channel is None:
cur_channel = ch
cur_channels.add(ch)
xs.append(x)
ys.append(y)
if len(buf) > 1_000_000:
del buf[:-262144]
self._finalize_current(xs, ys, cur_channels)
def _run_binary_stream(self, chunk_reader: SerialChunkReader):
xs: list[int] = []
ys: list[int] = []
cur_channel: Optional[int] = None
cur_channels: set[int] = set()
words = deque()
buf = bytearray()
while not self._stop.is_set():
data = chunk_reader.read_available()
if data:
buf += data
else:
time.sleep(0.0005)
continue
usable = len(buf) & ~1
if usable == 0:
continue
i = 0
while i < usable:
w = int(buf[i]) | (int(buf[i + 1]) << 8)
words.append(w)
i += 2
# Бинарный протокол:
# старт свипа (актуальный): 0xFFFF, 0xFFFF, 0xFFFF, (ch<<8)|0x0A
# старт свипа (legacy): 0xFFFF, 0xFFFF, channel, 0x0A0A
# точка: step, value_hi, value_lo, 0x000A
while len(words) >= 4:
w0 = int(words[0])
w1 = int(words[1])
w2 = int(words[2])
w3 = int(words[3])
if w0 == 0xFFFF and w1 == 0xFFFF and w2 == 0xFFFF and (w3 & 0x00FF) == 0x000A:
self._finalize_current(xs, ys, cur_channels)
xs.clear()
ys.clear()
cur_channels.clear()
cur_channel = (w3 >> 8) & 0x00FF
cur_channels.add(cur_channel)
for _ in range(4):
words.popleft()
continue
if w0 == 0xFFFF and w1 == 0xFFFF and w3 == 0x0A0A:
self._finalize_current(xs, ys, cur_channels)
xs.clear()
ys.clear()
cur_channels.clear()
cur_channel = w2
cur_channels.add(cur_channel)
for _ in range(4):
words.popleft()
continue
if w3 == 0x000A:
if cur_channel is not None:
cur_channels.add(cur_channel)
xs.append(w0)
value_u32 = (w1 << 16) | w2
ys.append(self._u32_to_i32(value_u32))
for _ in range(4):
words.popleft()
continue
# Поток может начаться с середины пакета; сдвигаемся по слову до ресинхронизации.
words.popleft()
del buf[:usable]
if len(buf) > 1_000_000:
del buf[:-262144]
self._finalize_current(xs, ys, cur_channels)
def run(self):
try: try:
self._src = SerialLineSource(self._port_path, self._baud, timeout=1.0) self._src = SerialLineSource(self._port_path, self._baud, timeout=1.0)
@ -150,66 +294,11 @@ class SweepReader(threading.Thread):
try: try:
chunk_reader = SerialChunkReader(self._src) chunk_reader = SerialChunkReader(self._src)
buf = bytearray() if self._bin_mode:
while not self._stop.is_set(): self._run_binary_stream(chunk_reader)
data = chunk_reader.read_available() else:
if data: self._run_ascii_stream(chunk_reader)
buf += data
else:
time.sleep(0.0005)
continue
while True:
nl = buf.find(b"\n")
if nl == -1:
break
line = bytes(buf[:nl])
del buf[: nl + 1]
if line.endswith(b"\r"):
line = line[:-1]
if not line:
continue
if line.startswith(b"Sweep_start"):
self._finalize_current(xs, ys, cur_channels)
xs.clear()
ys.clear()
cur_channel = None
cur_channels.clear()
continue
if len(line) >= 3:
parts = line.split()
if len(parts) >= 3 and (parts[0].lower() == b"s" or parts[0].lower().startswith(b"s")):
try:
if parts[0].lower() == b"s":
if len(parts) >= 4:
ch = int(parts[1], 10)
x = int(parts[2], 10)
y = int(parts[3], 10)
else:
ch = 0
x = int(parts[1], 10)
y = int(parts[2], 10)
else:
ch = int(parts[0][1:], 10)
x = int(parts[1], 10)
y = int(parts[2], 10)
except Exception:
continue
if cur_channel is None:
cur_channel = ch
cur_channels.add(ch)
xs.append(x)
ys.append(y)
if len(buf) > 1_000_000:
del buf[:-262144]
finally: finally:
try:
self._finalize_current(xs, ys, cur_channels)
except Exception:
pass
try: try:
if self._src is not None: if self._src is not None:
self._src.close() self._src.close()

9
rfg_adc_plotter/main.py Normal file → Executable file
View File

@ -77,6 +77,15 @@ def build_parser() -> argparse.ArgumentParser:
default="projector", default="projector",
help="Тип нормировки: projector (по огибающим в [-1000,+1000]) или simple (raw/calib)", help="Тип нормировки: projector (по огибающим в [-1000,+1000]) или simple (raw/calib)",
) )
parser.add_argument(
"--bin",
dest="bin_mode",
action="store_true",
help=(
"Бинарный протокол: старт свипа 0xFFFF,0xFFFF,0xFFFF,(CH<<8)|0x0A; "
"точки step,uint32(hi16,lo16),0x000A"
),
)
return parser return parser

2
run_dataplotter Executable file
View File

@ -0,0 +1,2 @@
#!/usr/bin/bash
python3 -m rfg_adc_plotter.main --bin --backend mpl $@