Debian Codegraph @

pymeasure/instruments/redpitaya/redpitaya_scpi.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2023 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25
26 import datetime
27 import numpy as np
28
29 from pymeasure.instruments import Instrument, Channel, SCPIMixin
30 from pymeasure.instruments.validators import truncated_range, strict_discrete_set
31
32 import logging
33 log = logging.getLogger(__name__)
34 log.addHandler(logging.NullHandler())
35
36
37 class DigitalChannelP(Channel):
38 """ A digital line of the P type"""
39
40 direction_in = Channel.control(
41 "DIG:PIN:DIR? DIO{ch}_P", "DIG:PIN:DIR %s,DIO{ch}_P",
42 """ Control a digital line to the given direction (True for 'IN' or False for 'OUT')""",
43 validator=strict_discrete_set,
44 map_values=True,
45 values={True: 'IN', False: 'OUT'},
46 )
47
48 enabled = Channel.control(
49 "DIG:PIN? DIO{ch}_P", "DIG:PIN DIO{ch}_P,%d",
50 """ Control the enabled state of the line (bool)""",
51 validator=strict_discrete_set,
52 map_values=True,
53 values={True: 1, False: 0},
54 )
55
56
57 class DigitalChannelN(Channel):
58 """ A digital line of the N type"""
59
60 direction_in = Channel.control(
61 "DIG:PIN:DIR? DIO{ch}_N", "DIG:PIN:DIR %s,DIO{ch}_N",
62 """ Control a digital line to the given direction (True for 'IN' or False for 'OUT')""",
63 validator=strict_discrete_set,
64 map_values=True,
65 values={True: 'IN', False: 'OUT'},
66 )
67
68 enabled = Channel.control(
69 "DIG:PIN? DIO{ch}_N", "DIG:PIN DIO{ch}_N,%d",
70 """ Control the enabled state of the line (bool)""",
71 validator=strict_discrete_set,
72 map_values=True,
73 values={True: 1, False: 0},
74 )
75
76
77 class DigitalChannelLed(Channel):
78 """ A LED digital line (Output only)"""
79
80 enabled = Channel.control(
81 "DIG:PIN? LED{ch}", "DIG:PIN LED{ch},%d",
82 """ Control the enabled state of the led (bool)""",
83 validator=strict_discrete_set,
84 map_values=True,
85 values={True: 1, False: 0},
86 )
87
88
89 class AnalogInputSlowChannel(Channel):
90 """ A slow analog input channel"""
91
92 voltage = Channel.measurement(
93 "ANALOG:PIN? AIN{ch}",
94 """ Measure the voltage on the corresponding analog input channel, range is [0, 3.3]V""",
95 )
96
97
98 class AnalogOutputSlowChannel(Channel):
99 """ A slow analog output channel"""
100
101 voltage = Channel.setting(
102 "ANALOG:PIN AOUT{ch}, %f",
103 """ Set the voltage on the corresponding analog input channel, range is [0, 1.8]V""",
104 validator=truncated_range,
105 values=[0, 1.8],
106 )
107
108
109 class AnalogInputFastChannel(Channel):
110
111 gain = Instrument.control(
112 "ACQ:SOUR{ch}:GAIN?", "ACQ:SOUR{ch}:GAIN %s",
113 """Control the gain of the selected fast analog input either 'LV' or 'HV'
114 (see jumpers on boards)
115
116 'LV' set the returned values in the range [-1, 1]V and 'HV' in the range [-20, 20]V
117 """,
118 validator=strict_discrete_set,
119 values=['LV', 'HV'],
120 )
121
122 def get_data(self, npts: int = None, format='ASCII') -> np.ndarray:
123 """ Read data from the buffer
124
125 :param npts: number of points to be read
126 :param format: either 'ASCII' or 'BIN', see :meth:acq_format
127 """
128 if npts is not None:
129 self.write(f"ACQ:SOUR{'{ch}'}:DATA:Old:N? {npts:.0f}")
130 else:
131 self.write("ACQ:SOUR{ch}:DATA?")
132
133 if format == 'ASCII':
134 data = self._read_from_ascii()
135 else:
136 data = self._read_from_binary()
137 return data
138
139 def _read_from_ascii(self) -> np.ndarray:
140 """ Read data from the buffer from ascii format, see :meth:acq_format
141 """
142 data_str = self.read()
143 return np.fromstring(data_str.strip('{}').encode(), sep=',')
144
145 def _read_from_binary(self) -> np.ndarray:
146 """ Read data from the buffer from binary format, see :meth:acq_format
147 """
148 self.read_bytes(1)
149 nint = int(self.read_bytes(1).decode())
150 length = int(self.read_bytes(nint).decode())
151 data = np.frombuffer(self.read_bytes(length), dtype=int)
152 self.read_bytes(2)
153 if self.gain == 'LV':
154 max_range = 2 * RedPitayaScpi.LV_MAX
155 else:
156 max_range = 2 * RedPitayaScpi.HV_MAX
157
158 return max_range * data / (2**16 - 1) - max_range / 2
159
160
161 class RedPitayaScpi(SCPIMixin, Instrument):
162 """This is the class for the Redpitaya reconfigurable board
163
164 The instrument is accessed using a TCP/IP Socket communication, that is an adapter in the form:
165 "TCPIP::x.y.z.k::port::SOCKET" where x.y.z.k is the IP address of the SCPI server
166 (that should be activated on the board) and port is the TCP/IP port number, usually 5000
167
168 To activate the SCPI server, you have to connect first the redpitaya to your computer/network
169 and enter the url address written on the network plug (on the redpitaya). It should be something
170 like "RP-F06432.LOCAL/" then browse the menu, open the Development application and activate the
171 SCPI server. When activating the server, you'll be notified with the IP/port address to use
172 with this Instrument.
173
174 :param ip_address: IP address to use, if `adapter` is None.
175 :param port: Port number to use, if `adapter` is None.
176 """
177
178 TRIGGER_SOURCES = ('DISABLED', 'NOW', 'CH1_PE', 'CH1_NE', 'CH2_PE', 'CH2_NE',
179 'EXT_PE', 'EXT_NE', 'AWG_PE', 'AWG_NE')
180 LV_MAX = 1
181 HV_MAX = 20
182 CLOCK = 125e6 # Hz
183 DELAY_NS = tuple(np.array(np.array(range(-2**13, 2**13+1)) * 1 / CLOCK * 1e9, dtype=int))
184
185 def __init__(self,
186 adapter=None,
187 ip_address: str = '169.254.134.87', port: int = 5000, name="Redpitaya SCPI",
188 read_termination='\r\n',
189 write_termination='\r\n',
190 **kwargs):
191
192 if adapter is None: # if None build it from the usual way as written in the documentation
193 adapter = f"TCPIP::{ip_address}::{port}::SOCKET"
194
195 super().__init__(
196 adapter,
197 name,
198 read_termination=read_termination,
199 write_termination=write_termination,
200 **kwargs)
201
202 dioN = Instrument.MultiChannelCreator(DigitalChannelN, list(range(7)), prefix='dioN')
203 dioP = Instrument.MultiChannelCreator(DigitalChannelP, list(range(7)), prefix='dioP')
204 led = Instrument.MultiChannelCreator(DigitalChannelLed, list(range(8)), prefix='led')
205
206 analog_in_slow = Instrument.MultiChannelCreator(AnalogInputSlowChannel, list(range(4)),
207 prefix='ainslow')
208 analog_out_slow = Instrument.MultiChannelCreator(AnalogOutputSlowChannel, list(range(4)),
209 prefix='aoutslow')
210
211 analog_in = Instrument.MultiChannelCreator(AnalogInputFastChannel, (1, 2), prefix='ain')
212
213 time = Instrument.control("SYST:TIME?",
214 "SYST:TIME %s",
215 """Control the time on board
216 time should be given as a datetime.time object""",
217 get_process=lambda _tstr:
218 datetime.time(*[int(split) for split in _tstr]),
219 set_process=lambda _time:
220 _time.strftime('%H,%M,%S'),
221 )
222
223 date = Instrument.control("SYST:DATE?",
224 "SYST:DATE %s",
225 """Control the date on board
226 date should be given as a datetime.date object""",
227 get_process=lambda dstr:
228 datetime.date(*[int(split) for split in dstr]),
229 set_process=lambda date: date.strftime('%Y,%m,%d'),
230 )
231
232 board_name = Instrument.measurement("SYST:BRD:Name?",
233 """Get the RedPitaya board name""")
234
235 def digital_reset(self):
236 """Reset the state of all digital lines"""
237 self.write("DIG:RST")
238
239 # ANALOG SECTION
240
241 def analog_reset(self):
242 """ Reset the voltage of all analog channels """
243 self.write("ANALOG:RST")
244
245 # ACQUISITION SECTION
246
247 def acquisition_start(self):
248 self.write("ACQ:START")
249
250 def acquisition_stop(self):
251 self.write("ACQ:STOP")
252
253 def acquisition_reset(self):
254 self.write("ACQ:RST")
255
256 # Acquisition Settings
257
258 decimation = Instrument.control(
259 "ACQ:DEC?", "ACQ:DEC %d",
260 """Control the decimation (int) as 2**n with n in range [0, 16]
261 The sampling rate is given as 125MS/s / decimation
262 """,
263 validator=strict_discrete_set,
264 values=[2**n for n in range(17)],
265 cast=int,
266 )
267
268 average_skipped_samples = Instrument.control(
269 "ACQ:AVG?", "ACQ:AVG %s",
270 """Control the use of skipped samples (if decimation > 1) to average the returned
271 acquisition array (bool)""",
272 validator=strict_discrete_set,
273 map_values=True,
274 values={True: 'ON', False: 'OFF'},
275 )
276
277 acq_units = Instrument.control(
278 "ACQ:DATA:Units?", "ACQ:DATA:Units %s",
279 """Control the output data units (str), either 'RAW', or 'VOLTS' (default)""",
280 validator=strict_discrete_set,
281 values=['RAW', 'VOLTS'],
282 )
283
284 buffer_length = Instrument.measurement(
285 "ACQ:BUF:SIZE?",
286 """Measure the size of the buffer, that is the number of points of the acquisition""",
287 cast=int,
288 )
289
290 acq_format = Instrument.setting(
291 "ACQ:DATA:FORMAT %s",
292 """Set the format of the retrieved buffer data (str), either 'BIN', or 'ASCII' (default)""",
293 validator=strict_discrete_set,
294 values=['BIN', 'ASCII'],
295 )
296
297 # Acquisition Trigger
298
299 acq_trigger_source = Instrument.setting(
300 "ACQ:TRig %s",
301 """Set the trigger source (str), one of RedPitayaScpi.TRIGGER_SOURCES.
302 PE and NE means respectively Positive and Negative edge
303 """,
304 validator=strict_discrete_set,
305 values=TRIGGER_SOURCES,
306 )
307
308 acq_trigger_status = Instrument.measurement(
309 "ACQ:TRig:STAT?",
310 """Get the trigger status (bool), if True the trigger as been fired (or is disabled)""",
311 map_values=True,
312 values={True: 'TD', False: 'WAIT'},
313 )
314
315 acq_trigger_position = Instrument.measurement(
316 "ACQ:TPOS?",
317 """Get the position within the buffer where the trigger event happened""",
318 cast=int,
319 )
320
321 acq_buffer_filled = Instrument.measurement(
322 "ACQ:TRig:FILL?",
323 """Get the status of the buffer(bool), if True the buffer is full""",
324 map_values=True,
325 values={True: 1, False: 0},
326 )
327
328 acq_trigger_delay_samples = Instrument.control(
329 "ACQ:TRig:DLY?", "ACQ:TRig:DLY %d",
330 """Control the trigger delay in number of samples (int) in the range [-8192, 8192]""",
331 validator=truncated_range,
332 cast=int,
333 values=[-2**13, 2**13],
334 )
335
336 # direct call to the SCPI command "ACQ:TRig:DLY:NS?" seems not to be working...
337 @property
338 def acq_trigger_delay_ns(self):
339 """Control the trigger delay in nanoseconds (int) in the range [-8192, 8192] / CLOCK"""
340 return int(self.acq_trigger_delay_samples * 1 / self.CLOCK * 1e9)
341
342 @acq_trigger_delay_ns.setter
343 def acq_trigger_delay_ns(self, delay_ns: int):
344 delay_sample = int(delay_ns * self.CLOCK / 1e9)
345 self.acq_trigger_delay_samples = delay_sample
346
347 # not working
348 # acq_trigger_delay_ns = Instrument.control(
349 # "ACQ:TRig:DLY:NS?", "ACQ:TRig:DLY:NS %d",
350 # """Control the trigger delay in nanoseconds (int) multiple of the board clock period
351 # (1/RedPitayaSCPI.CLOCK)""",
352 # validator=truncated_discrete_set,
353 # values=DELAY_NS,
354 # cast=int,
355 # )
356
357 acq_trigger_level = Instrument.control(
358 "ACQ:TRig:LEV?", "ACQ:TRig:LEV %f",
359 """Control the level of the trigger in volts
360 The allowed range should be dynamically set depending on the gain settings either +-LV_MAX
361 or +- HV_MAX
362 """,
363 validator=truncated_range,
364 values=[-LV_MAX, LV_MAX],
365 dynamic=True,
366 )