Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update TSPDevice.load_script() to accept raw strings #308

Merged
merged 10 commits into from
Sep 19, 2024
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,20 @@ Things to be included in the next release go here.

- Added a config option (`default_visa_timeout`) to specify the default VISA timeout for all initial VISA device connections.
- Added a new function, `register_additional_usbtmc_mapping()`, to enable users to add USBTMC connection information for devices that don't have native support for USBTMC connections in `tm_devices` yet.
- Added `TSPDevice.export_buffers()` to write tsp buffer data fields to file, default is comma separated values with buffer names header.

### Changed

- Switched all workflows to use the new [`tektronix/python-package-ci-cd`](https://github.com/tektronix/python-package-ci-cd) reusable workflows.
- Reduced the out-of-the box `default_visa_timeout` value from 30 seconds to 5 seconds.
- _**SEMI-BREAKING CHANGE**_: Changed the `USB_MODEL_ID_LOOKUP` constant to use `SupportedModels` as keys instead of values to make the documentation clearer.
- _**SEMI-BREAKING CHANGE**_: Changed the `DEVICE_DRIVER_MODEL_MAPPING` constant to use `SupportedModels` as keys instead of values to make the documentation clearer.
- _**SEMI-BREAKING CHANGE**_: Changed the input parameter order in `TSPDevice.load_script()` and updated it to accept raw string input in addition to the `file_path` parameter for the script content.
- Verbosity with `PIDevice.write()` now handles multiline input printouts.

### Deprecated

- Renamed `TSPDevice.write_buffers()` to `TSPDevice.export_buffers()` for clarity.

### Fixed

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
# Capture the path to the script file and load it to working memory.
print(pathlib.Path.cwd())
fileandpath = f"{pathlib.Path.cwd()}\\KEI2400_TTI_Driver\\simple_resistivity_measure.tsp"
smu2400.load_script(fileandpath, script_name="resistivityscript", run_script=True)
smu2400.load_script(script_name="resistivityscript", file_path=fileandpath, run_script=True)

# Call the resistivity measurement function on the instrument with the desired current,
# then print the result to the console.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def capture_pulse_i(inst: SMU2651A) -> None:

smua.source.output = 0

inst.write_buffers(I_FILENAME, "smua.nvbuffer1.timestamps", "smua.nvbuffer2", "smua.nvbuffer1")
inst.export_buffers(I_FILENAME, "smua.nvbuffer1.timestamps", "smua.nvbuffer2", "smua.nvbuffer1")


def capture_pulse_v(inst: SMU2651A) -> None:
Expand Down Expand Up @@ -216,7 +216,7 @@ def capture_pulse_v(inst: SMU2651A) -> None:

smua.source.output = 0

inst.write_buffers(V_FILENAME, "smua.nvbuffer1.timestamps", "smua.nvbuffer2", "smua.nvbuffer1")
inst.export_buffers(V_FILENAME, "smua.nvbuffer1.timestamps", "smua.nvbuffer2", "smua.nvbuffer1")


# RUN TEST
Expand Down
5 changes: 5 additions & 0 deletions src/tm_devices/drivers/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,11 @@ def close(self) -> None:
def has_errors(self) -> bool:
"""Check if the device has any errors.

!!! warning
In v3 this method will return a tuple containing a bool and a list of instances of
device error info dataclasses (this will replace
[`get_eventlog_status()`][tm_devices.drivers.pi.pi_device.PIDevice]).

Returns:
A boolean indicating if any errors were found in the device.
"""
Expand Down
3 changes: 1 addition & 2 deletions src/tm_devices/drivers/pi/ieee488_2_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,7 @@ def opc(self, write: bool = False) -> str:
if write:
self._pi_device.write("opc()")
return ""
self.wai()
return self._pi_device.query("print([[1]])")
return self._pi_device.query("waitcomplete() print([[1]])")

def rst(self) -> None:
r"""Send the Reset (``reset()``) command."""
Expand Down
14 changes: 13 additions & 1 deletion src/tm_devices/drivers/pi/pi_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ def get_eventlog_status(self) -> Tuple[bool, str]:
Returns:
Boolean indicating no error, String containing concatenated contents of event log.
"""
# TODO: in v3 - This will be deprecated by the has_errors

def turn_channel_off(self, channel_str: str) -> None:
"""Turn off the specified channel.
Expand Down Expand Up @@ -867,7 +868,18 @@ def write(self, command: str, opc: bool = False, verbose: bool = True) -> None:
SystemError: ``*OPC?`` did not return "1" after sending the command.
"""
if self._verbose and verbose:
print_with_timestamp(f"({self._name_and_alias}) Write >> {command!r}")
if "\n" in command:
# Format any multiline command to print out with a single timestamp
# followed by as many (whitespace padded) f'>> {cmd}' lines as it has
commands_iter = iter(repr(command.strip()).split("\\n"))
spaces = " " * len(
print_with_timestamp(
f"({self._name_and_alias}) Write >> {next(commands_iter)}"
).split(">> ")[0]
)
print(*[f"{spaces}>> {cmd}" for cmd in commands_iter], sep="\n")
else:
print_with_timestamp(f"({self._name_and_alias}) Write >> {command!r}")

try:
self._visa_resource.write(command)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,10 @@ def set_and_check( # noqa: PLR0913

def load_script(
self,
file_path: Union[str, os.PathLike[str]], # noqa: ARG002
script_name: str = "", # noqa: ARG002
script_name: str, # noqa: ARG002
*,
script_body: str = "", # noqa: ARG002
file_path: Union[str, os.PathLike[str], None] = None, # noqa: ARG002
run_script: bool = False, # noqa: ARG002
to_nv_memory: bool = False, # noqa: ARG002
) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,10 @@ def set_and_check( # noqa: PLR0913

def load_script(
self,
file_path: Union[str, os.PathLike[str]], # noqa: ARG002
script_name: str = "", # noqa: ARG002
script_name: str, # noqa: ARG002
*,
script_body: str = "", # noqa: ARG002
file_path: Union[str, os.PathLike[str], None] = None, # noqa: ARG002
run_script: bool = False, # noqa: ARG002
to_nv_memory: bool = False, # noqa: ARG002
) -> None:
Expand Down
78 changes: 47 additions & 31 deletions src/tm_devices/drivers/pi/tsp_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

import warnings

from abc import ABC
from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING, Union

Expand Down Expand Up @@ -80,6 +82,26 @@ def expect_esr(self, esr: Union[int, str], error_string: str = "") -> Tuple[bool

return result, failure_message

def export_buffers(self, filepath: str, *args: str, sep: str = ",") -> None:
ldantek marked this conversation as resolved.
Show resolved Hide resolved
"""Export one or more of the device's buffers to the given filepath.

Args:
filepath: A string representing the path of the file to write to.
args: The buffer name(s) to export.
sep: The delimiter used to separate data. Defaults to ",".
"""
with open(filepath, mode="w", encoding="utf-8") as file:
buffer_data = self.get_buffers(*args)
column_length = max(len(x) for x in buffer_data.values())
file.write(sep.join(buffer_data) + "\n")
for index in range(column_length):
file.write(
sep.join(
[str(ls[index]) if index < len(ls) else "" for ls in buffer_data.values()]
)
+ "\n"
)

def get_buffers(self, *args: str) -> Dict[str, List[float]]:
"""Get the contents of one or more buffers on the device.

Expand Down Expand Up @@ -127,38 +149,36 @@ def get_buffers(self, *args: str) -> Dict[str, List[float]]:

def load_script(
self,
file_path: Union[str, os.PathLike[str]],
script_name: str = "",
script_name: str,
*,
script_body: str = "",
file_path: Union[str, os.PathLike[str], None] = None,
run_script: bool = False,
to_nv_memory: bool = False,
) -> None:
"""Upload a TSP script to the instrument.

Args:
file_path: The file path of the script to read from the Python code's filesystem and
load on the instrument.
script_name: A string indicating what to name the script being loaded on the instrument,
if empty, 'loadfuncs' is used as the script name.
script_name: A string indicating what to name the script being loaded on the instrument.
script_body: TSP content to load on the instrument, overwritten if `file_path` defined.
file_path: a *.tsp file from the local filesystem to read and use as the `script_body`.
run_script: Boolean indicating if the script should be run immediately after loading.
to_nv_memory: Boolean indicating if the script is to be saved to non-volatile memory.
"""
if not script_name:
script_name = "loadfuncs"
if file_path is not None:
# script_body argument is overwritten by file contents
with open(file_path, encoding="utf-8") as script_tsp:
script_body = script_tsp.read().strip()

# Check if the script exists, delete it if it does
self.write(f"if {script_name} ~= nil then script.delete('{script_name}') end")

with open(file_path, encoding="utf-8") as script:
self.write(f"loadscript {script_name}")
while tsp_command := script.readline():
# TODO: Check and Send Valid Commands
self.write(tsp_command.strip())
self.write("endscript")
# Load the script
self.write(f"loadscript {script_name}\n{script_body}\nendscript")

# Save to NV Memory
if to_nv_memory:
self.write(f"{script_name}.save()")
# Save to Non-Volatile Memory (script definition survives power cycle)
if to_nv_memory:
self.write(f"{script_name}.save()")

if run_script:
self.run_script(script_name)
Expand Down Expand Up @@ -250,18 +270,14 @@ def write_buffers(self, filepath: str, *args: str, sep: str = ",") -> None:
args: The buffer name(s) to export.
sep: The delimiter used to separate data. Defaults to ",".
"""
with open(filepath, mode="w", encoding="utf-8") as file:
buffer_data = self.get_buffers(*args)
column_length = max(len(x) for x in buffer_data.values())
file.write(sep.join(buffer_data) + "\n")
for index in range(column_length):
file.write(
sep.join(
[str(ls[index]) if index < len(ls) else "" for ls in buffer_data.values()]
)
+ "\n"
)
# TODO: Deprecation - remove in next major version v3
warnings.warn(
DeprecationWarning("Use export_buffers(...) instead."),
stacklevel=2,
)
self.export_buffers(filepath, *args, sep=sep)

################################################################################################
# Private Methods
################################################################################################

################################################################################################
# Private Methods
################################################################################################
2 changes: 1 addition & 1 deletion tests/sim_devices/daq/daq6510.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ devices:
r: KEITHLEY INSTRUMENTS,MODEL DAQ6510,04089762,1.6.3
- q: waitcomplete()
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: eventlog.clear()
- q: status.clear()
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/dmm/dmm6500.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ devices:
r: KEITHLEY INSTRUMENTS,MODEL DMM6500,01418035,1.0.0
- q: waitcomplete()
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: eventlog.clear()
- q: status.clear()
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/dmm/dmm7510.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ devices:
r: KEITHLEY INSTRUMENTS,MODEL DMM7510,00000170,1.0.0
- q: waitcomplete()
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: eventlog.clear()
- q: status.clear()
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/dmm/dmm7512.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ devices:
r: KEITHLEY INSTRUMENTS,MODEL DMM7512,00000171,1.0.0
- q: waitcomplete()
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: eventlog.clear()
- q: status.clear()
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/smu/smu2450.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ devices:
r: Keithley Instruments Inc., Model 2450, 01419964, 3.3.5
- q: waitcomplete()
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: eventlog.clear()
- q: status.clear()
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/smu/smu2460.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ devices:
r: Keithley Instruments Inc., Model 2460, 01419964, 3.3.5
- q: waitcomplete()
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: eventlog.clear()
- q: status.clear()
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/smu/smu2461.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ devices:
r: Keithley Instruments Inc., Model 2461, 01419964, 3.3.5
- q: waitcomplete()
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: eventlog.clear()
- q: status.clear()
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/smu/smu2470.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ devices:
r: Keithley Instruments Inc., Model 2470, 01419964, 3.3.5
- q: waitcomplete()
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: eventlog.clear()
- q: status.clear()
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/smu/smu2601a.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ devices:
- q: print(status.standard.enable)
r: 1
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: reset()
- q: status.request_enable = 1
Expand Down
9 changes: 3 additions & 6 deletions tests/sim_devices/smu/smu2601b.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,8 @@ devices:
r: Keithley Instruments Inc., Model 2601B, 4498311, 3.3.5
- q: print(available(gpib))
r: 'true'
- q: loadscript loadfuncs
- q: loadscript tsp_function
- q: print("TEK")
- q: '"""Sample script used in test_smu.py."""'
- q: endscript
- q: loadscript loadfuncs\n"""Sample script used in test_smu.py."""\nprint("TEK")\nendscript
- q: loadscript tsp_function\n"""Sample script used in test_smu.py."""\nprint("TEK")\nendscript
- q: loadfuncs.save()
- q: loadfuncs()
- q: errorqueue.clear()
Expand All @@ -20,7 +17,7 @@ devices:
- q: print(status.standard.enable)
r: 1
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: reset()
- q: status.request_enable = 1
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/smu/smu2601b_pulse.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ devices:
- q: print(status.standard.enable)
r: 1
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: reset()
- q: status.request_enable = 1
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/smu/smu2602a.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ devices:
- q: print(status.standard.enable)
r: 1
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: reset()
- q: status.request_enable = 1
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/smu/smu2602b.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ devices:
- q: print(status.standard.enable)
r: 1
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: reset()
- q: status.request_enable = 1
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/smu/smu2604a.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ devices:
- q: print(status.standard.enable)
r: 1
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: reset()
- q: status.request_enable = 1
Expand Down
2 changes: 1 addition & 1 deletion tests/sim_devices/smu/smu2604b.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ devices:
- q: print(status.standard.enable)
r: 1
- q: opc()
- q: print([[1]])
- q: waitcomplete() print([[1]])
r: 1
- q: reset()
- q: status.request_enable = 1
Expand Down
Loading
Loading