-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscopeController.py
More file actions
195 lines (159 loc) · 6.73 KB
/
scopeController.py
File metadata and controls
195 lines (159 loc) · 6.73 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""Tektronix TBS1104 oscilloscope controller (VISA).
Revision history
----------------
2026-04 : Initial release. Originally created by Andak Consulting.
License
-------
MIT License
Copyright (c) 2026 Andak Consulting
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import threading
import numpy as np
import pyvisa
_SCOPE_MODELS = ("TBS", "TDS", "TPS", "MDO", "MSO", "DPO", "TDO")
TIMEBASE_VALUES: tuple[float, ...] = (
2.5e-9, 5e-9,
1e-8, 2.5e-8, 5e-8,
1e-7, 2.5e-7, 5e-7,
1e-6, 2.5e-6, 5e-6,
1e-5, 2.5e-5, 5e-5,
1e-4, 2.5e-4, 5e-4,
1e-3, 2.5e-3, 5e-3,
1e-2, 2.5e-2, 5e-2,
1e-1, 2.5e-1, 5e-1,
1.0, 2.5, 5.0,
10.0, 25.0, 50.0,
)
VOLTS_PER_DIV_VALUES: tuple[float, ...] = (
2e-3, 5e-3,
1e-2, 2e-2, 5e-2,
1e-1, 2e-1, 5e-1,
1.0, 2.0, 5.0,
)
# Tektronix TBS1000B / TDS1000 / TDS2000 accepted probe attenuation values.
PROBE_VALUES: tuple[int, ...] = (1, 10, 20, 50, 100, 500, 1000)
def scan_scopes() -> list[tuple[str, str]]:
"""Return (resource_str, idn) for every Tektronix oscilloscope on the VISA bus."""
results = []
rm = pyvisa.ResourceManager()
try:
for resource in rm.list_resources():
try:
inst = rm.open_resource(resource)
inst.timeout = 2000
idn = inst.query("*IDN?").strip()
inst.close()
idn_upper = idn.upper()
if any(f"TEKTRONIX,{m}" in idn_upper for m in _SCOPE_MODELS):
results.append((resource, idn))
except Exception:
pass
finally:
rm.close()
return results
class ScopeController:
def __init__(self):
self.rm = pyvisa.ResourceManager()
self.scope = None
# Serialise VISA access so a GUI-thread set_timebase() cannot interleave
# with an in-flight CURVE? on the live-acquisition worker.
self.lock = threading.Lock()
def connect(self, resource_str: str) -> str:
self.scope = self.rm.open_resource(resource_str)
self.scope.timeout = 5000
idn = self.scope.query("*IDN?").strip()
return idn
def close(self):
if self.scope:
try:
self.scope.close()
except Exception:
pass
self.scope = None
try:
self.rm.close()
except Exception:
pass
def set_timebase(self, seconds_per_div: float):
with self.lock:
self.scope.write(f"HORizontal:SCAle {seconds_per_div:.6e}")
def get_timebase(self) -> float:
with self.lock:
return float(self.scope.query("HORizontal:SCAle?"))
def set_channel_scale(self, channel: int, volts_per_div: float):
with self.lock:
self.scope.write(f"CH{channel}:SCAle {volts_per_div:.6e}")
def get_channel_scale(self, channel: int) -> float:
with self.lock:
return float(self.scope.query(f"CH{channel}:SCAle?"))
def set_channel_display(self, channel: int, on: bool):
with self.lock:
self.scope.write(f"SELect:CH{channel} {'ON' if on else 'OFF'}")
def get_channel_display(self, channel: int) -> bool:
with self.lock:
raw = self.scope.query(f"SELect:CH{channel}?").strip()
return raw not in ("0", "OFF")
def set_channel_probe(self, channel: int, factor: int):
with self.lock:
self.scope.write(f"CH{channel}:PROBe {factor:d}")
def get_channel_probe(self, channel: int) -> int:
"""Return the attenuation factor (e.g. 1, 10, 100) currently set on the scope."""
with self.lock:
raw = self.scope.query(f"CH{channel}:PROBe?").strip()
# TBS/TDS returns a single NR1/NR3 like "1.0E0"; DPO series may return
# a semicolon-delimited structure where the factor is the second field.
if ";" in raw:
try:
return int(float(raw.split(";")[1]))
except (IndexError, ValueError):
pass
return int(float(raw))
def start_continuous(self):
with self.lock:
self.scope.write("ACQ:STOPA RUNST")
self.scope.write("ACQ:STATE RUN")
def stop(self):
with self.lock:
self.scope.write("ACQ:STATE STOP")
def get_waveform(self, channel: int) -> tuple[np.ndarray, np.ndarray]:
"""Read and scale waveform from the given channel (1-based).
Returns (time_array, voltage_array) as numpy float arrays.
"""
with self.lock:
self.scope.write(f"DATA:SOURCE CH{channel}")
self.scope.write("DATA:WIDTH 1")
self.scope.write("DATA:ENC RIBinary")
y_mult = float(self.scope.query("WFMPRE:YMULT?"))
y_off = float(self.scope.query("WFMPRE:YOFF?"))
y_zero = float(self.scope.query("WFMPRE:YZERO?"))
self.scope.timeout = 10000
raw = self.scope.query_binary_values(
"CURVE?", datatype="b", is_big_endian=True, header_fmt="ieee"
)
self.scope.timeout = 5000
x_increment = float(self.scope.query("WFMPRE:XINCR?"))
x_zero = float(self.scope.query("WFMPRE:XZERO?"))
num_points = int(self.scope.query("WFMPRE:NR_PT?"))
# Probe attenuation is applied by the scope itself (set via CH<n>:PROBe),
# so y_mult/y_off already yield true-input voltages. No host-side factor.
voltage = (np.array(raw, dtype=float) - y_off) * y_mult + y_zero
time_arr = np.arange(num_points, dtype=float) * x_increment + x_zero
# Defensive: if CURVE? returned fewer samples than NR_PT reports
# (older firmware / acquisition still running), clip so the two arrays align.
n = min(len(time_arr), len(voltage))
return time_arr[:n], voltage[:n]