rs-scope-mcp 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ """rs-scope-mcp: control and data harvesting for Rohde & Schwarz oscilloscopes.
2
+
3
+ Supported and bench-tested: RTB2 / RTB2000 series (RTB2002, RTB2004).
4
+
5
+ Layers (bottom up):
6
+ transport - raw SCPI socket, IEEE 488.2 block data, timeouts
7
+ registry - every documented SCPI command, validation, search
8
+ instrument - connection, sync, error queue, safety gate, batching
9
+ sim - a simulated RTB2 that speaks SCPI on a local socket (tests, demos)
10
+ server - the MCP server
11
+ """
12
+
13
+ __version__ = "0.1.2"
@@ -0,0 +1,377 @@
1
+ """Layer 5 (part): compact summaries of harvested data.
2
+
3
+ The rule for everything that goes back to the assistant: summaries up, details on
4
+ request, always with counts and pointers. These functions turn megabytes of samples
5
+ and hundreds of frames into a few hundred tokens of facts.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from collections import Counter
10
+
11
+ import numpy as np
12
+
13
+
14
+ def _r(x: float | None, digits: int = 4) -> float | None:
15
+ if x is None or not np.isfinite(x):
16
+ return None
17
+ return float(f"{x:.{digits}g}")
18
+
19
+
20
+ def analog_summary(values: np.ndarray, dt: float, codes_max: int | None = None) -> dict:
21
+ """Levels, RMS, dominant frequency (rising mean crossings) and clipping."""
22
+ v = values.astype(np.float64, copy=False)
23
+ if v.size == 0:
24
+ return {"n": 0}
25
+ vmin, vmax, mean = float(v.min()), float(v.max()), float(v.mean())
26
+ rms = float(np.sqrt(np.mean(v * v)))
27
+ ac_rms = float(v.std())
28
+ out: dict = {"n": int(v.size), "duration_s": _r(v.size * dt), "min_v": _r(vmin), "max_v": _r(vmax),
29
+ "vpp": _r(vmax - vmin), "mean_v": _r(mean), "rms_v": _r(rms), "ac_rms_v": _r(ac_rms)}
30
+ # frequency from rising crossings of the midpoint with hysteresis
31
+ mid, hyst = (vmax + vmin) / 2, 0.1 * (vmax - vmin)
32
+ if vmax - vmin > 1e-6:
33
+ above = v > mid + hyst
34
+ below = v < mid - hyst
35
+ state = np.where(above, 1, np.where(below, -1, 0))
36
+ nz = state[state != 0]
37
+ idx = np.flatnonzero(state)
38
+ if nz.size > 2:
39
+ rises = idx[1:][(nz[1:] == 1) & (nz[:-1] == -1)]
40
+ if rises.size >= 2:
41
+ period = float(np.median(np.diff(rises))) * dt
42
+ out["frequency_hz"] = _r(1 / period) if period > 0 else None
43
+ out["cycles"] = int(rises.size)
44
+ if codes_max is not None and codes_max >= 65000:
45
+ out["clipping"] = True
46
+ elif vmax - vmin > 0:
47
+ top = np.mean(v >= vmax - 1e-9)
48
+ bot = np.mean(v <= vmin + 1e-9)
49
+ if top > 0.02 and bot > 0.02 and "frequency_hz" not in out:
50
+ out["clipping_suspected"] = True
51
+ return out
52
+
53
+
54
+ def pod_edges(values: np.ndarray, t0: float, dt: float, first_channel: int = 0,
55
+ max_edges: int = 0) -> dict:
56
+ """Per-channel edge statistics from pod bytes (bit n = channel first_channel+n)."""
57
+ chans = {}
58
+ for bit in range(8):
59
+ b = ((values >> bit) & 1).astype(np.int8)
60
+ d = np.diff(b)
61
+ idx = np.flatnonzero(d)
62
+ name = f"D{first_channel + bit}"
63
+ info: dict = {"edges": int(idx.size), "high_fraction": _r(float(b.mean()), 3)}
64
+ if idx.size == 0:
65
+ info["level"] = int(b[0]) if b.size else None
66
+ else:
67
+ if idx.size > 1:
68
+ widths = np.diff(idx) * dt
69
+ info["min_pulse_s"] = _r(float(widths.min()))
70
+ info["median_pulse_s"] = _r(float(np.median(widths)))
71
+ if widths.min() > 0:
72
+ # NRZ data (UART, CAN): bit rate = 1 / shortest pulse.
73
+ # A clock line toggles twice per period: frequency = 1 / (2 x typical pulse).
74
+ info["nrz_bitrate_estimate"] = _r(1 / float(widths.min()))
75
+ info["clock_hz_if_clock"] = _r(1 / (2 * float(np.median(widths))))
76
+ info["first_edge_s"] = _r(t0 + (idx[0] + 1) * dt)
77
+ if max_edges:
78
+ info["edges_s"] = [_r(t0 + (i + 1) * dt, 6) for i in idx[:max_edges]]
79
+ chans[name] = info
80
+ active = {k: v for k, v in chans.items() if v["edges"]}
81
+ idle = {k: v.get("level") for k, v in chans.items() if not v["edges"]}
82
+ return {"n": int(values.size), "duration_s": _r(values.size * dt), "active": active, "idle_levels": idle}
83
+
84
+
85
+ def _ascii(data: list[int]) -> str:
86
+ # UART words can be 9 bits: the text is in the low 8
87
+ return "".join(chr(b & 0xFF) if 32 <= (b & 0xFF) < 127 else "." for b in data if b is not None and b >= 0)
88
+
89
+
90
+ def frames_summary(decoded: dict, preview: int = 5) -> dict:
91
+ frames = decoded.get("frames", [])
92
+ status = Counter(str(f.get("status")) for f in frames)
93
+ out: dict = {"bus": decoded.get("bus"), "type": decoded.get("type"), "frames": decoded.get("frame_count"),
94
+ "harvested": len(frames), "status": dict(status), "seconds": decoded.get("seconds")}
95
+ if decoded.get("warnings"):
96
+ out["warnings"] = decoded["warnings"]
97
+ for key in ("address", "id"):
98
+ c = Counter(f.get(key) for f in frames if f.get(key) is not None)
99
+ if c:
100
+ out[f"{key}es" if key == "address" else "ids"] = [
101
+ {key: (f"0x{a:02X}" if isinstance(a, int) else a), "frames": n} for a, n in c.most_common(10)]
102
+ payload = []
103
+ for f in frames:
104
+ payload.extend(x for x in (f.get("data") or f.get("mosi") or []) if x is not None)
105
+ out["bytes"] = len(payload)
106
+ text = _ascii(payload)
107
+ if text and sum(ch != "." for ch in text) > 0.6 * len(text):
108
+ out["ascii"] = text[:200]
109
+ bad = [f["index"] for f in frames if str(f.get("status", "OK")).upper() not in ("OK", "NONE")]
110
+ if bad:
111
+ out["non_ok_frames"] = bad[:20]
112
+
113
+ def slim(f: dict) -> dict:
114
+ s = {k: v for k, v in f.items() if v not in (None, [], "") and k != "word_status"}
115
+ for k in ("data", "mosi", "miso"):
116
+ if k in s and isinstance(s[k], list):
117
+ s[k] = " ".join(f"{b:02X}" for b in s[k][:32] if b is not None) + (" …" if len(s[k]) > 32 else "")
118
+ return s
119
+
120
+ out["first"] = [slim(f) for f in frames[:preview]]
121
+ if len(frames) > preview:
122
+ out["last"] = [slim(f) for f in frames[-2:]]
123
+ return out
124
+
125
+
126
+ def bode_summary(f: np.ndarray, g: np.ndarray, p: np.ndarray) -> dict:
127
+ if f.size == 0:
128
+ return {"points": 0}
129
+ i_pk = int(np.argmax(g))
130
+ ref = float(np.median(g[: max(3, f.size // 10)])) # low-frequency gain as the reference
131
+ out: dict = {"points": int(f.size), "range_hz": [_r(float(f[0])), _r(float(f[-1]))],
132
+ "peak_gain_db": _r(float(g[i_pk])), "peak_at_hz": _r(float(f[i_pk])),
133
+ "low_freq_gain_db": _r(ref), "high_freq_gain_db": _r(float(np.median(g[-max(3, f.size // 10):])))}
134
+ for name, level in (("minus_3db", ref - 3.0), ("minus_6db", ref - 6.0)):
135
+ below = np.flatnonzero(g < level)
136
+ if below.size and below[0] > 0:
137
+ k = below[0]
138
+ # interpolate on a log-frequency axis
139
+ x0, x1 = np.log10(f[k - 1]), np.log10(f[k])
140
+ y0, y1 = g[k - 1], g[k]
141
+ x = x0 + (level - y0) * (x1 - x0) / (y1 - y0) if y1 != y0 else x0
142
+ out[f"{name}_hz"] = _r(float(10 ** x))
143
+ out[f"phase_at_{name}_deg"] = _r(float(np.interp(x, np.log10(f), p)))
144
+ hi = out["high_freq_gain_db"] or 0
145
+ lo = out["low_freq_gain_db"] or 0
146
+ if g.max() - max(lo, hi) > 3:
147
+ out["shape"] = "band-pass or resonant"
148
+ elif lo - hi > 6:
149
+ out["shape"] = "low-pass"
150
+ elif hi - lo > 6:
151
+ out["shape"] = "high-pass"
152
+ else:
153
+ out["shape"] = "flat within 6 dB"
154
+ return out
155
+
156
+
157
+ def spectrum_peaks(f0: float, df: float, mags: np.ndarray, n: int = 10, min_prominence_db: float = 10) -> dict:
158
+ m = mags.astype(np.float64)
159
+ if m.size < 3:
160
+ return {"points": int(m.size)}
161
+ floor = float(np.median(m))
162
+ idx = np.flatnonzero((m[1:-1] > m[:-2]) & (m[1:-1] >= m[2:])) + 1
163
+ idx = idx[m[idx] > floor + min_prominence_db]
164
+ idx = idx[np.argsort(m[idx])[::-1]][:n]
165
+ peaks = sorted(({"freq_hz": _r(f0 + i * df), "dbv": _r(float(m[i]), 3)} for i in idx),
166
+ key=lambda d: d["freq_hz"])
167
+ return {"points": int(m.size), "range_hz": [_r(f0), _r(f0 + (m.size - 1) * df)],
168
+ "noise_floor_dbv": _r(floor, 3), "peaks": peaks}
169
+
170
+
171
+ def minmax_decimate(values: np.ndarray, t0: float, dt: float, t_start: float | None, t_end: float | None,
172
+ max_points: int = 400) -> dict:
173
+ """A window of a series reduced to at most max_points [t, min, max] rows."""
174
+ n = values.size
175
+ i0 = 0 if t_start is None else max(0, int((t_start - t0) / dt))
176
+ i1 = n if t_end is None else min(n, int((t_end - t0) / dt) + 1)
177
+ seg = values[i0:i1]
178
+ if seg.size == 0:
179
+ return {"rows": []}
180
+ step = max(1, int(np.ceil(seg.size / max_points)))
181
+ rows = []
182
+ for j in range(0, seg.size, step):
183
+ chunk = seg[j:j + step]
184
+ rows.append([_r(t0 + (i0 + j) * dt, 6), _r(float(chunk.min())), _r(float(chunk.max()))])
185
+ return {"window_s": [_r(t0 + i0 * dt, 6), _r(t0 + i1 * dt, 6)], "samples": int(seg.size),
186
+ "samples_per_row": step, "columns": ["t_s", "min", "max"], "rows": rows}
187
+
188
+
189
+ # ---------------------------------------------------------------------------------- envelope
190
+ def envelope(values: np.ndarray, dt: float, carrier_hz: float | None = None) -> dict:
191
+ """Envelope of a modulated or keyed carrier: AM depth, rise/fall time, crest factor.
192
+
193
+ The envelope is the peak of |v - mean| over windows of about two carrier periods. AM depth
194
+ m = (Emax - Emin) / (Emax + Emin). Rise and fall are 10-90 % times of the first full
195
+ transition of the envelope (CW keying shape).
196
+ """
197
+ v = values.astype(np.float64, copy=False)
198
+ v = v - float(np.mean(v))
199
+ if v.size < 16:
200
+ return {"n": int(v.size)}
201
+ if not carrier_hz:
202
+ carrier_hz = analog_summary(values, dt).get("frequency_hz")
203
+ if not carrier_hz:
204
+ return {"error": "no carrier found; pass carrier_hz"}
205
+ win = max(2, round(2.0 / (carrier_hz * dt)))
206
+ n = v.size // win
207
+ if n < 8:
208
+ return {"error": "record too short for this carrier; use a longer timebase"}
209
+ env = np.abs(v[: n * win]).reshape(n, win).max(axis=1)
210
+ edt = win * dt
211
+ e_max, e_min = float(np.percentile(env, 99)), float(np.percentile(env, 1))
212
+ out: dict = {"carrier_hz": _r(carrier_hz), "window_s": _r(edt), "points": int(n),
213
+ "envelope_max_v": _r(e_max), "envelope_min_v": _r(e_min),
214
+ "am_depth": _r((e_max - e_min) / (e_max + e_min), 3) if e_max + e_min > 0 else None,
215
+ "crest_factor": _r(float(np.max(np.abs(v)) / np.sqrt(np.mean(v * v))), 3)}
216
+ lo, hi = e_min + 0.1 * (e_max - e_min), e_min + 0.9 * (e_max - e_min)
217
+ if e_max - e_min > 0.2 * e_max:
218
+ def first_cross(arr: np.ndarray, level: float, rising: bool, start: int = 0) -> int | None:
219
+ seg = arr[start:]
220
+ idx = np.flatnonzero(seg >= level) if rising else np.flatnonzero(seg <= level)
221
+ return int(idx[0]) + start if idx.size else None
222
+
223
+ # rising edge: last time below 10 % before first time above 90 %
224
+ i_hi = first_cross(env, hi, True, first_cross(env, lo, False) or 0)
225
+ if i_hi is not None:
226
+ below = np.flatnonzero(env[:i_hi] <= lo)
227
+ if below.size:
228
+ out["rise_10_90_s"] = _r((i_hi - below[-1]) * edt)
229
+ i_lo = first_cross(env, lo, False, i_hi)
230
+ if i_lo is not None:
231
+ above = np.flatnonzero(env[i_hi:i_lo] >= hi)
232
+ if above.size:
233
+ out["fall_90_10_s"] = _r((i_lo - (i_hi + above[-1])) * edt)
234
+ if out.get("rise_10_90_s") is not None:
235
+ out["note"] = ("rise/fall resolution is one envelope window "
236
+ f"({_r(edt)} s); for CW keying, under ~1 ms rise means key clicks")
237
+ return out
238
+
239
+
240
+ # ---------------------------------------------------------------------------------- bus identification
241
+ _STD_BAUD = [300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 76800, 100000, 115200,
242
+ 230400, 250000, 460800, 500000, 921600, 1000000, 2000000]
243
+
244
+
245
+ def identify_bus(values: np.ndarray, t0: float, dt: float, first_channel: int = 0) -> dict:
246
+ """Guess what the active logic lines carry (I2C, SPI, UART, PWM, clock) from their edges.
247
+
248
+ Heuristics, not proof: confirm by setting up the decoder the guess names and checking that
249
+ frames decode with status OK.
250
+ """
251
+ lines = {}
252
+ for bit in range(8):
253
+ b = ((values >> bit) & 1).astype(np.int8)
254
+ idx = np.flatnonzero(np.diff(b))
255
+ if idx.size < 4:
256
+ continue
257
+ w = np.diff(idx) * dt
258
+ wmin = float(w.min())
259
+ # bit time: the mean of the shortest pulses (sampling makes them jitter by one sample)
260
+ unit = float(np.mean(w[w < 1.5 * wmin]))
261
+ q = w / unit
262
+ quantized = float(np.mean(np.abs(q - np.round(q)) < 0.2))
263
+ # idle = the level held during the longest quiet stretch (robust when the record starts
264
+ # in the middle of a transfer)
265
+ bounds = np.concatenate(([0], idx + 1, [b.size]))
266
+ runs = np.diff(bounds)
267
+ if runs[0] >= 2 * float(np.median(runs)) and runs[0] >= 4:
268
+ idle = int(b[0]) # quiet before the first edge (a trigger on the activity)
269
+ else:
270
+ idle = int(b[bounds[int(np.argmax(runs))]])
271
+ # bursts: gaps much longer than the typical pulse
272
+ med = float(np.median(w))
273
+ gaps = int(np.sum(w > 8 * med))
274
+ # periodic: pulse widths alternate between at most two values (clock or PWM)
275
+ hi_w = w[0::2] if b[idx[0] + 1] == 1 else w[1::2]
276
+ lo_w = w[1::2] if b[idx[0] + 1] == 1 else w[0::2]
277
+ period = float(np.median(hi_w[: min(hi_w.size, lo_w.size)] + lo_w[: min(hi_w.size, lo_w.size)])) \
278
+ if min(hi_w.size, lo_w.size) else None
279
+ regular = bool(hi_w.size >= 2 and lo_w.size >= 2 and np.std(hi_w) < 0.1 * np.mean(hi_w)
280
+ and np.std(lo_w) < 0.1 * np.mean(lo_w))
281
+ lines[f"D{first_channel + bit}"] = {
282
+ "bit": bit, "edges": int(idx.size), "idle": idle, "high_fraction": float(b.mean()),
283
+ "min_pulse_s": wmin, "unit_pulse_s": unit, "median_pulse_s": med, "quantized": quantized, "bursts": gaps,
284
+ "regular": regular, "period_s": period,
285
+ "duty": float(np.median(hi_w) / period) if period else None,
286
+ "first_edge": int(idx[0])}
287
+ if not lines:
288
+ return {"guess": "no activity", "lines": {}}
289
+ names = list(lines)
290
+ out: dict = {"active": names}
291
+
292
+ def rnd(d: dict) -> dict:
293
+ return {k: (_r(v) if isinstance(v, float) else v) for k, v in d.items() if k not in ("bit", "first_edge")}
294
+
295
+ out["lines"] = {k: rnd(v) for k, v in lines.items()}
296
+ # a clock-like line in bursts: many edges, constant half-period inside bursts
297
+ clocks = [k for k, v in lines.items() if v["quantized"] > 0.9 and v["median_pulse_s"] <= 1.5 * v["min_pulse_s"]
298
+ and v["bursts"] > 0]
299
+ # periodic lines (clocks, PWM): constant high and low times, however long the low time is
300
+ steady = [k for k, v in lines.items() if v["regular"]]
301
+ guess, conf, setup = "unknown", "low", None
302
+ if steady and len(lines) == 1:
303
+ k = steady[0]
304
+ v = lines[k]
305
+ f = 1 / v["period_s"] if v["period_s"] else None
306
+ if v["duty"] is not None and 0.4 < v["duty"] < 0.6:
307
+ guess, conf = f"clock or square wave on {k}", "medium"
308
+ else:
309
+ guess, conf = f"PWM on {k}", "medium"
310
+ out["frequency_hz"] = _r(f) if f else None
311
+ out["duty"] = _r(v["duty"], 3) if v["duty"] is not None else None
312
+ out["high_time_s"] = _r(v["duty"] * v["period_s"]) if v["duty"] and v["period_s"] else None
313
+ if f and 40 <= f <= 500 and out["high_time_s"] and 0.0008 <= out["high_time_s"] <= 0.0025:
314
+ guess += " (servo/ESC-style: 1-2 ms pulse)"
315
+ elif clocks:
316
+ clk = max(clocks, key=lambda k: lines[k]["edges"])
317
+ others = [k for k in names if k != clk]
318
+ # idle levels of a clocked bus: every line's level in the longest pause of the clock
319
+ cb = ((values >> lines[clk]["bit"]) & 1).astype(np.int8)
320
+ cidx = np.flatnonzero(np.diff(cb))
321
+ cbounds = np.concatenate(([0], cidx + 1, [cb.size]))
322
+ g = int(np.argmax(np.diff(cbounds)))
323
+ mid = (cbounds[g] + cbounds[g + 1]) // 2
324
+ for k in names:
325
+ lines[k]["idle"] = int((values[mid] >> lines[k]["bit"]) & 1)
326
+ both_idle_high = lines[clk]["idle"] == 1 and all(lines[o]["idle"] == 1 for o in others)
327
+ # chip select: a line that holds one level while the clock toggles (frames the bursts)
328
+ clk_bit = lines[clk]["bit"]
329
+ clk_idx = np.flatnonzero(np.diff(((values >> clk_bit) & 1).astype(np.int8)))
330
+ cs = []
331
+ for o in others:
332
+ ob = ((values >> lines[o]["bit"]) & 1).astype(np.int8)
333
+ during = ob[clk_idx]
334
+ if not clk_idx.size:
335
+ continue
336
+ active = round(float(during.mean())) # the level it holds while the clock runs
337
+ frac = float(np.mean(during == active))
338
+ share = float(np.mean(ob == active))
339
+ if frac > 0.97 and share < 0.999 and 2 <= lines[o]["edges"] < lines[clk]["edges"] / 2:
340
+ cs.append(o)
341
+ lines[o]["idle"] = 1 - active # idle is the inactive level
342
+ cs.sort(key=lambda o: lines[o]["edges"])
343
+ data = [o for o in others if o not in cs]
344
+ f_clk = 1 / (2 * lines[clk]["median_pulse_s"])
345
+ out["clock_line"], out["clock_hz"] = clk, _r(f_clk)
346
+ if cs and data:
347
+ guess, conf = "SPI", "medium"
348
+ out["chip_select"] = cs[0]
349
+ out["data_lines"] = data
350
+ setup = {"BUS<b>:TYPE": "SPI", "CLOCk:SOURce": clk, "CS:SOURce": cs[0],
351
+ "CS:POLarity": "NEG" if lines[cs[0]]["idle"] == 1 else "POS",
352
+ "MOSI/MISO:SOURce": data}
353
+ elif len(data) == 1 and both_idle_high:
354
+ guess, conf = "I2C", "medium"
355
+ setup = {"BUS<b>:TYPE": "I2C", "CLOCk:SOURce": clk, "DATA:SOURce": data[0]}
356
+ elif not data:
357
+ guess, conf = f"bursts of clock on {clk}", "low"
358
+ else:
359
+ guess = "synchronous bus (clock + data); try SPI"
360
+ else:
361
+ # single asynchronous line with quantized pulses: UART
362
+ cand = [k for k, v in lines.items() if v["quantized"] > 0.8]
363
+ if cand:
364
+ k = max(cand, key=lambda x: lines[x]["edges"])
365
+ v = lines[k]
366
+ raw = 1 / v["unit_pulse_s"]
367
+ baud = min(_STD_BAUD, key=lambda b: abs(b - raw) / b)
368
+ guess, conf = "UART", "medium" if abs(baud - raw) / baud < 0.03 else "low"
369
+ out["line"], out["baud_measured"], out["baud_standard"] = k, _r(raw), baud
370
+ out["polarity"] = "idle high (normal)" if v["idle"] == 1 else "idle low (inverted, e.g. SBUS)"
371
+ setup = {"BUS<b>:TYPE": "UART", "DATA:SOURce": k, "BAUDrate": baud,
372
+ "POLarity": "IDLH" if v["idle"] == 1 else "IDLL"}
373
+ out["guess"], out["confidence"] = guess, conf
374
+ if setup:
375
+ out["decoder_setup"] = setup
376
+ out["confirm"] = "set up this decoder, capture BUSn, and check the frames decode with status OK"
377
+ return out
rs_scope_mcp/cli.py ADDED
@@ -0,0 +1,166 @@
1
+ """`rs-scope` command line: bench checks without an AI in the loop.
2
+
3
+ rs-scope --host 192.168.1.50 idn
4
+ rs-scope --host 192.168.1.50 query "CHAN1:SCAL?"
5
+ rs-scope --host 192.168.1.50 write "TIM:SCAL 1e-3"
6
+ rs-scope --host 192.168.1.50 screenshot shot.png
7
+ rs-scope --host 192.168.1.50 tree-diff
8
+ rs-scope search "i2c frame"
9
+ rs-scope describe "BUS<b>:I2C:FRAMe<n>:DATA?"
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import re
17
+ import sys
18
+ import time
19
+ from pathlib import Path
20
+
21
+ from .instrument import GuardedCommand, Instrument, InstrumentError, ValidationError
22
+ from .registry import Registry, describe
23
+ from .transport import TransportError
24
+
25
+
26
+ def _inst(a) -> Instrument:
27
+ if not a.host:
28
+ sys.exit("error: --host (or RS_SCOPE_HOST) is required for this command")
29
+ i = Instrument(a.host, a.port, timeout=a.timeout, validate=not a.no_validate)
30
+ i.connect()
31
+ return i
32
+
33
+
34
+ def cmd_tree_diff(a) -> int:
35
+ """Compare the registry with the firmware's own command list (SYSTem:TREE?)."""
36
+ i = _inst(a)
37
+ t0 = time.monotonic()
38
+ tree = i.transport.query("SYSTem:TREE?", timeout=90) # ~60 kB, ~16 s on FW 03.000
39
+ fw = sorted({h.strip() for h in re.split(r"[;\n]", tree) if h.strip() and not h.strip().startswith("&")})
40
+ reg = i.registry
41
+ manual_only = [h for h in fw if not any(c.source == "manual" for c, _, _ in reg.match_header(h))]
42
+ unknown = [h for h in fw if not reg.match_header(h)]
43
+ out = {
44
+ "firmware": i.idn.get("firmware"),
45
+ "model": i.idn.get("model"),
46
+ "firmware_headers": len(fw),
47
+ "documented_in_manual": len(fw) - len(manual_only),
48
+ "undocumented": len(manual_only),
49
+ "unknown_to_registry": unknown[:200],
50
+ "seconds": round(time.monotonic() - t0, 1),
51
+ }
52
+ if a.save:
53
+ name = f"{i.idn.get('model', 'RTB2')}-{i.idn.get('firmware', 'unknown')}.tree"
54
+ path = Path(a.save) / name
55
+ path.write_text("\n".join(fw) + "\n")
56
+ out["saved"] = str(path)
57
+ print(json.dumps(out, indent=1))
58
+ return 0
59
+
60
+
61
+ WIRING = {
62
+ "analog": "Aux Out -> 50 ohm feed-through terminator -> CH1",
63
+ "full": "Aux Out -> 50 ohm terminator -> CH1, and pattern generator P0..P3 -> logic probe D0..D3",
64
+ }
65
+
66
+
67
+ def cmd_demo(a) -> int:
68
+ from .demo import Demo, scenes_for
69
+ if a.list:
70
+ print(f"wiring ({a.level}): {WIRING[a.level]}")
71
+ for s in scenes_for(a.level):
72
+ print(f" {s.id:12s} {s.level:6s} {s.title}: {s.caption}")
73
+ return 0
74
+ if not a.yes:
75
+ print(f"The demo drives the generator outputs. Wiring for '{a.level}': {WIRING[a.level]}.\n"
76
+ "Run again with --yes once it is wired.", file=sys.stderr)
77
+ return 2
78
+ i = _inst(a)
79
+ d = Demo(i, level=a.level, dwell=a.dwell, loops=a.loops, only=a.only,
80
+ shots=Path(a.shots) if a.shots else None)
81
+ try:
82
+ result = d.run()
83
+ except KeyboardInterrupt:
84
+ d.stop()
85
+ result = {"stopped": True}
86
+ print(json.dumps(result, indent=1))
87
+ return 0
88
+
89
+
90
+ def main(argv=None) -> int:
91
+ ap = argparse.ArgumentParser(prog="rs-scope", description="R&S RTB2 bench CLI (rs-scope-mcp)")
92
+ ap.add_argument("--host", default=os.environ.get("RS_SCOPE_HOST"))
93
+ ap.add_argument("--port", type=int, default=int(os.environ.get("RS_SCOPE_PORT", "5025")))
94
+ ap.add_argument("--timeout", type=float, default=10.0)
95
+ ap.add_argument("--no-validate", action="store_true", help="send commands unknown to the registry")
96
+ sub = ap.add_subparsers(dest="cmd", required=True)
97
+ sub.add_parser("idn")
98
+ q = sub.add_parser("query")
99
+ q.add_argument("line", nargs="+")
100
+ w = sub.add_parser("write")
101
+ w.add_argument("line")
102
+ w.add_argument("--confirm", action="store_true")
103
+ s = sub.add_parser("screenshot")
104
+ s.add_argument("path", nargs="?", default="rtb2-screenshot.png")
105
+ td = sub.add_parser("tree-diff", help="compare the registry with the firmware's SYSTem:TREE?")
106
+ td.add_argument("--save", metavar="DIR", help="save the tree for src/rs_scope_mcp/data/rtb2/firmware/")
107
+ se = sub.add_parser("search")
108
+ se.add_argument("terms", nargs="+")
109
+ d = sub.add_parser("describe")
110
+ d.add_argument("header")
111
+ sub.add_parser("stats", help="registry statistics")
112
+ dm = sub.add_parser("demo", help="play the demo scenes on the scope (see docs/DEMO.md)")
113
+ dm.add_argument("--level", choices=["analog", "full"], default="analog")
114
+ dm.add_argument("--dwell", type=float, default=12.0, help="seconds per scene")
115
+ dm.add_argument("--loops", type=int, default=1, help="0 = until Ctrl-C")
116
+ dm.add_argument("--only", nargs="*", help="scene ids")
117
+ dm.add_argument("--shots", help="save a screenshot of every scene into this folder")
118
+ dm.add_argument("--list", action="store_true", help="list the scenes and the wiring")
119
+ dm.add_argument("--yes", action="store_true",
120
+ help="confirm the wiring: the demo drives the generator and pattern-generator outputs")
121
+ a = ap.parse_args(argv)
122
+
123
+ try:
124
+ if a.cmd == "idn":
125
+ print(json.dumps(_inst(a).connect(), indent=1))
126
+ elif a.cmd == "query":
127
+ i = _inst(a)
128
+ if len(a.line) == 1:
129
+ print(json.dumps(i.query(a.line[0], check_errors=True).as_dict(), indent=1))
130
+ else:
131
+ print(json.dumps(dict(zip(a.line, i.query_many(a.line))), indent=1))
132
+ elif a.cmd == "write":
133
+ print(json.dumps(_inst(a).write(a.line, confirm=a.confirm).as_dict(), indent=1))
134
+ elif a.cmd == "screenshot":
135
+ i = _inst(a)
136
+ i.write("HCOPy:LANGuage PNG")
137
+ data = i.query_block("HCOPy:DATA?", timeout=30)
138
+ with open(a.path, "wb") as f:
139
+ f.write(data)
140
+ print(f"wrote {a.path} ({len(data)} bytes)")
141
+ elif a.cmd == "tree-diff":
142
+ return cmd_tree_diff(a)
143
+ elif a.cmd == "search":
144
+ reg = Registry.default()
145
+ for c in reg.search(" ".join(a.terms)):
146
+ print(f"{c.header:55s} {c.kind:9s} p{c.page:<4d} {c.summary[:70]}")
147
+ elif a.cmd == "describe":
148
+ reg = Registry.default()
149
+ c = reg.by_header(a.header)
150
+ if not c:
151
+ print("not found", file=sys.stderr)
152
+ return 1
153
+ print(json.dumps(describe(c, verbose=True), indent=1, ensure_ascii=False))
154
+ elif a.cmd == "demo":
155
+ return cmd_demo(a)
156
+ elif a.cmd == "stats":
157
+ reg = Registry.default()
158
+ print(json.dumps({"meta": reg.meta, "subsystems": reg.subsystems()}, indent=1))
159
+ except (ValidationError, GuardedCommand, InstrumentError, TransportError) as e:
160
+ print(f"error: {e}", file=sys.stderr)
161
+ return 2
162
+ return 0
163
+
164
+
165
+ if __name__ == "__main__":
166
+ raise SystemExit(main())
File without changes
File without changes