"""GPIB transport implementation via PyVISA.
Provides a :class:`BaseTransport` implementation that communicates with
instruments over a GPIB (IEEE-488) bus using the :mod:`pyvisa` library.
PyVISA is an optional run-time dependency; an :exc:`ImportError` is raised
at construction time if it is not installed.
"""
from __future__ import annotations
import logging
import re
from collections.abc import Iterator
from contextlib import contextmanager
from time import perf_counter, sleep
from typing import TYPE_CHECKING
from stoner_measurement.instruments.errors import InstrumentError
from stoner_measurement.instruments.transport.base import BaseTransport
from stoner_measurement.telemetry import timed_call
if TYPE_CHECKING:
import pyvisa
import pyvisa.resources
#: Regular expression that parses a GPIB VISA resource string of the form
#: ``GPIB[board]::primary[::secondary][::INSTR]``.
_GPIB_RESOURCE_RE = re.compile(r"GPIB([0-9]*)::([0-9]+)(?:::([0-9]+))?(?:::INSTR)?", re.IGNORECASE)
_DEFAULT_GPIB_READ_TERMINATOR = None
_DEFAULT_GPIB_WRITE_TERMINATOR = "\n"
_DEFAULT_K6221_SERIAL_POLL = 0.05
_DEFAULT_READ_POLL = 0.01
logger = logging.getLogger(__name__)
def _get_stb_from_response(response):
"""Try to extract a status byte from a bytestring response."""
parts = response.split(b";")
try:
rc = int(float(parts[-1]))
response = b";".join(parts[:-1])
return rc, response
except ValueError as exc:
raise InstrumentError(f"{response} did not seem to contain a status byte.") from exc
[docs]
class GpibTransport(BaseTransport):
"""GPIB transport using PyVISA.
Wraps a PyVISA ``GPIBInstrument`` resource to provide the standard
:class:`BaseTransport` interface. The VISA resource string is
constructed as ``GPIB<board>::<address>[::<secondary_address>]::INSTR``.
Attributes:
address (int):
GPIB primary address of the instrument (0–30).
board (int):
GPIB board (interface) index. Defaults to ``0``.
secondary_address (int | None):
Secondary address (0–30), or ``None`` when not used. Zero is a
real secondary address and is distinct from ``None``.
timeout (float):
Read timeout in seconds. Defaults to ``2.0``.
Examples:
>>> from stoner_measurement.instruments.transport import GpibTransport
>>> t = GpibTransport(address=22)
>>> t.address
22
>>> t.board
0
>>> t.resource_string
'GPIB0::22::INSTR'
"""
def __init__(
self,
address: int,
board: int = 0,
timeout: float = 2.0,
use_mav: bool = True,
poll_time: float = 0.01,
command_complete_mask: int | None = None,
secondary_address: int | None = None,
) -> None:
"""Initialise the GPIB transport.
Args:
address (int):
GPIB primary address (0–30).
Keyword Parameters:
board (int):
GPIB board index. Defaults to ``0``.
timeout (float):
Read timeout in seconds. Defaults to ``2.0``.
use_mav (bool):
Use the 4th bit of the Status Byte to control reading. Default True
poll_time (float):
Time in seconds to wait to see if the status byte will show MAV.
command_complete_mask (int | None):
Optional instrument-specific status-byte mask indicating that
command execution is complete. When supplied, a completed
query that never asserts MAV is bounded by *timeout*. Defaults
to ``None`` because this bit is not standard across instruments.
secondary_address (int | None):
GPIB secondary address (0–30), or ``None`` for none.
Raises:
ImportError:
If :mod:`pyvisa` is not installed.
"""
try:
import pyvisa as _pyvisa # noqa: F401
except ImportError as exc:
raise ImportError(
"pyvisa is required for GpibTransport. Install it with: pip install pyvisa"
) from exc
super().__init__(timeout=timeout)
for name, value in (("address", address), ("board", board), ("secondary_address", secondary_address)):
if value is None and name == "secondary_address":
continue
if not isinstance(value, int) or value < 0 or (name != "board" and value > 30):
raise ValueError(f"Invalid GPIB {name}: {value!r}.")
self.address = address
self.board = board
self.secondary_address = secondary_address
self._connection_attempt = 0
self._resource: pyvisa.resources.GPIBInstrument | None = None
self._rm: pyvisa.ResourceManager | None = None
self._read_termination: str | None = _DEFAULT_GPIB_READ_TERMINATOR
self._poll_time: float = poll_time or _DEFAULT_READ_POLL
self._use_mav = use_mav
self._command_complete_mask = command_complete_mask
self._status_error_mask: int | None = 0x04
[docs]
@classmethod
def from_resource_string(
cls,
resource_string: str,
timeout: float = 2.0,
use_mav: bool = True,
poll_time: float = 0.01,
command_complete_mask: int | None = None,
) -> GpibTransport:
"""Construct a :class:`GpibTransport` from a VISA resource string.
Parses ``GPIB[board]::primary[::secondary][::INSTR]``. An omitted
board defaults to zero; an omitted secondary address means none.
Args:
resource_string (str):
VISA resource string, e.g. ``"GPIB0::22::INSTR"``.
Keyword Parameters:
timeout (float):
Read timeout in seconds. Defaults to ``2.0``.
Returns:
(GpibTransport):
A new :class:`GpibTransport` instance.
Raises:
ValueError:
If *resource_string* does not match the expected GPIB format.
ImportError:
If :mod:`pyvisa` is not installed.
Examples:
>>> from stoner_measurement.instruments.transport import GpibTransport
>>> t = GpibTransport.from_resource_string("GPIB0::14::INSTR")
>>> t.address
14
>>> t.board
0
>>> t.resource_string
'GPIB0::14::INSTR'
"""
m = _GPIB_RESOURCE_RE.fullmatch(resource_string.strip())
if not m:
raise ValueError(
f"Cannot parse GPIB resource string {resource_string!r}. "
"Expected format: 'GPIB[board]::primary[::secondary][::INSTR]'."
)
board = int(m.group(1) or 0)
address = int(m.group(2))
return cls(
address=address,
board=board,
timeout=timeout,
use_mav=use_mav,
poll_time=poll_time,
command_complete_mask=command_complete_mask,
secondary_address=int(m.group(3)) if m.group(3) is not None else None,
)
@property
def resource_string(self) -> str:
"""VISA resource string for this GPIB address.
Returns:
(str):
Canonical VISA string including the secondary address, if set.
Examples:
>>> from stoner_measurement.instruments.transport import GpibTransport
>>> GpibTransport(address=14, board=1).resource_string
'GPIB1::14::INSTR'
"""
secondary = "" if self.secondary_address is None else f"::{self.secondary_address}"
return f"GPIB{self.board}::{self.address}{secondary}::INSTR"
def _visa_call(self, stage, function, *args, **kwargs):
"""Run one native operation with optional connection timing diagnostics."""
connection = f"{id(self):x}/{self._connection_attempt}"
return timed_call(self.resource_string, connection, stage, function, *args, **kwargs)
[docs]
def open(self) -> None:
"""Open the GPIB resource via PyVISA.
Raises:
ConnectionError:
If the resource cannot be opened.
"""
import pyvisa
try:
self._connection_attempt += 1
self._rm = self._visa_call("resource_manager", pyvisa.ResourceManager)
self._resource = self._visa_call("open_resource", self._rm.open_resource, self.resource_string)
self._visa_call("set_timeout", setattr, self._resource, "timeout", int(self._timeout * 1000))
self._visa_call("set_send_end", setattr, self._resource, "send_end", True)
self._visa_call("set_read_termination", setattr, self._resource, "read_termination", self._read_termination)
self._is_open = True
self._log_comms_traffic("IEEE", "Connection opened.")
except pyvisa.VisaIOError as exc:
raise ConnectionError(
f"Cannot open GPIB resource {self.resource_string!r}: {exc}"
) from exc
[docs]
def close(self) -> None:
"""Close this transport's GPIB resource.
PyVISA shares one :class:`ResourceManager` between instances. Closing
that manager here would also close resources owned by other active
transports, so its process-level lifetime is left to PyVISA.
"""
if self._resource is not None:
self._visa_call("close_resource", self._resource.close)
self._resource = None
self._rm = None
self._is_open = False
self._log_comms_traffic("IEEE", "Connection closed.")
[docs]
def write(self, data: bytes, slow: int | None = None) -> None:
"""Write *data* to the GPIB instrument.
Args:
data (bytes):
Raw bytes to transmit. The bytes are decoded as ASCII before
being passed to PyVISA's ``write_raw``.
Keyword Arguments:
slow (int|none, None):
Whether to except the response to be slow and thus to pause for
*slow* milliseconds.
Raises:
ConnectionError:
If the transport is not open.
"""
if self._resource is None:
raise ConnectionError("GPIB transport is not open.")
self._log_comms_traffic("TX", data)
self._visa_call("write_raw", self._resource.write_raw, data)
if slow is not None:
sleep(slow / 1000)
rc = self._visa_call("write_serial_poll", self._resource.read_stb)
if self._status_error_mask is not None and rc & self._status_error_mask:
raise InstrumentError(f"Bad return status byte from {data.decode()}: STB={rc}")
return rc
[docs]
def read(self, num_bytes: int | None = None) -> bytes:
"""Read one response frame from the GPIB instrument.
Keyword Arguments:
num_bytes (int | None, None):
Optional maximum frame size for this call. When ``None``,
the transport uses the protocol-defined frame-size limit.
Returns:
(bytes):
Bytes received.
Raises:
ConnectionError:
If the transport is not open.
TimeoutError:
If no data arrives within :attr:`timeout` seconds.
"""
import pyvisa
if self._resource is None:
raise ConnectionError("GPIB transport is not open.")
frame_limit = self._resolve_max_frame_size(num_bytes)
deadline = perf_counter() + max(0.0, self._timeout)
last_status_byte: int | None = None
try:
response = b""
while self._use_mav: # Loop until the instrument reports message available.
last_status_byte = self.read_status_byte()
if last_status_byte is not None and last_status_byte & 16:
break
if (
self._command_complete_mask is not None
and last_status_byte is not None
and not last_status_byte & self._command_complete_mask
):
deadline = perf_counter() + max(0.0, self._timeout)
if perf_counter() >= deadline:
raise TimeoutError(
f"Timeout waiting for MAV from "
f"GPIB address {self.address}; "
f"last STB={last_status_byte}."
)
sleep(self._poll_time)
while (
self._use_mav and self.read_status_byte() & 16
) or not response: # Loop until we don;'t have a message available.
if self._use_mav and perf_counter() >= deadline:
raise TimeoutError(
f"Timeout reading from GPIB address {self.address}; "
f"last STB={last_status_byte}."
)
frame = self._visa_call("read_raw", self._resource.read_raw, frame_limit)
response += frame
if self._use_mav:
sleep(self._poll_time)
self._log_comms_traffic("RX", response)
return response
except pyvisa.errors.VisaIOError as exc:
logger.error(f"Timeout reading from GPIB address {self.address}: {exc}")
raise TimeoutError(f"Timeout reading from GPIB address {self.address}: {exc}") from exc
except TimeoutError:
raise
except Exception as exc:
logger.error("Exception in GPIB read {exc}\n{format_exc()}")
raise InstrumentError("Hit an error in read") from exc
@property
def transport_address(self) -> str:
"""Return the VISA resource string for this GPIB instrument.
Returns:
(str):
VISA resource string, e.g. ``"GPIB0::22::INSTR"``.
Examples:
>>> from stoner_measurement.instruments.transport import GpibTransport
>>> GpibTransport(address=22).transport_address
'GPIB0::22::INSTR'
"""
return self.resource_string
def _apply_timeout(self, value: float) -> None:
"""Update the PyVISA timeout on a live connection.
PyVISA expresses timeout in milliseconds.
"""
if self._resource is not None:
self._resource.timeout = int(value * 1000)
def _apply_protocol(self, protocol: object) -> None:
"""Apply protocol-specific read termination settings.
Args:
protocol (object):
Protocol instance supplied by the owning instrument.
"""
terminator = getattr(
protocol,
"gpib_terminator",
getattr(protocol, "terminator", _DEFAULT_GPIB_READ_TERMINATOR),
)
if terminator is None:
self._read_termination = None
elif isinstance(terminator, bytes):
self._read_termination = terminator.decode("latin-1")
else:
self._read_termination = str(terminator)
if self._resource is not None:
self._resource.read_termination = self._read_termination
self._status_error_mask = getattr(protocol, "status_error_mask", 0x04)
self._use_mav = bool(getattr(protocol, "gpib_use_mav", self._use_mav))
logger.info(
f"Termination sort for {self._resource} {self._read_termination=} {terminator=}"
)
[docs]
def read_status_byte(self) -> int | None:
"""Return the IEEE 488.2 status byte via a GPIB serial poll.
Performs an out-of-band serial poll (PyVISA ``read_stb()``) without
transmitting any command to the instrument. This is the preferred
mechanism for checking the GPIB status byte because it does not
consume a response from the instrument's output buffer.
Returns:
(int | None):
The 8-bit status byte, or ``None`` if the transport is not
currently open.
Examples:
>>> from stoner_measurement.instruments.transport import GpibTransport
>>> t = GpibTransport(address=22)
>>> t.read_status_byte() is None # not open
True
"""
if self._resource is None:
return None
stb = self._visa_call("read_serial_poll", self._resource.read_stb)
self._log_comms_traffic("IEEE", f"{stb=}")
return stb
[docs]
@contextmanager
def suppress_status_error_check(self) -> Iterator[None]:
"""Temporarily disable rejection of writes with the error bit set."""
status_error_mask = self._status_error_mask
self._status_error_mask = None
try:
yield
finally:
self._status_error_mask = status_error_mask
[docs]
def wait_for_srq(self, timeout: float) -> bool | None:
"""Wait for the GPIB service-request line without command polling."""
if self._resource is None:
return None
import pyvisa
try:
self._resource.wait_for_srq(timeout=max(1, round(timeout * 1000.0)))
except pyvisa.VisaIOError as exc:
if exc.error_code == pyvisa.constants.StatusCode.error_timeout:
return False
raise
self._log_comms_traffic("IEEE", "SRQ asserted")
return True
[docs]
def flush(self) -> None:
"""Send IEEE 488.2 Device Clear to the instrument and reset the interface.
Calls the PyVISA ``clear()`` method, which sends the Selected Device
Clear (SDC) message over the GPIB bus. This resets the instrument's
parser and discards any bytes queued in its output buffer, preventing
stale responses from old commands being misread after a reconnect.
If the resource is not open or Device Clear fails, the exception is
ignored and logged at debug level.
"""
if self._resource is None:
return
import pyvisa
try:
self._visa_call("device_clear", self._resource.clear)
self._log_comms_traffic("IEEE", "Connection flushed.")
except pyvisa.VisaIOError as exc:
logger.debug("Ignoring GPIB Device Clear failure for %s: %s", self.resource_string, exc)
[docs]
def send_group_execute_trigger(self) -> None:
"""Send an IEEE-488 GET (Group Execute Trigger) for this instrument."""
if self._resource is None:
raise ConnectionError("GPIB transport is not open.")
import pyvisa
try:
self._resource.assert_trigger()
self._log_comms_traffic("IEEE", "GET asserted.")
except pyvisa.VisaIOError as exc:
raise ConnectionError(f"Cannot assert GET on {self.resource_string!r}: {exc}") from exc
[docs]
class PassThroughGpibTransport(GpibTransport):
"""Passthrough Keithley 6221 GPIB transport.
Subclasses a GPIBTransport so that commands are wrapped in the SYST:COMM:SER:[SEND|ENT?]
SCPI commands of a Keithley 6221 current source. This is primarily intentended for
communicating with an attached Keithley 2182A nanovoltmeter, but could in principle be used
for other instruments supports IEEE488.2 common comands.
Attributes:
address (int):
GPIB primary address of the instrument (0–30).
board (int):
GPIB board (interface) index. Defaults to ``0``.
timeout (float):
Read timeout in seconds. Defaults to ``2.0``.
Examples:
>>> from stoner_measurement.instruments.transport import GpibTransport
>>> t = GpibTransport(address=22)
>>> t.address
22
>>> t.board
0
>>> t.resource_string
'GPIB0::22::INSTR'
"""
def __init__(
self,
address: int,
board: int = 0,
timeout: float = 2.0,
use_mav: bool = True,
poll_time: float = 0.01,
command_complete_mask: int | None = None,
max_read_chunks: int = 64,
secondary_address: int | None = None,
) -> None:
"""Initialise the GPIB transport.
Args:
address (int):
GPIB primary address (0–30) of the 6221.
Keyword Parameters:
board (int):
GPIB board index. Defaults to ``0``.
timeout (float):
Read timeout in seconds. Defaults to ``2.0``.
max_read_chunks (int):
Maximum number of ``SYST:COMM:SER:ENT?`` chunks to poll while
collecting one relayed response.
secondary_address (int | None):
GPIB secondary address of the 6221, or ``None`` for none.
Raises:
ImportError:
If :mod:`pyvisa` is not installed.
"""
try:
import pyvisa as _pyvisa # noqa: F401
except ImportError as exc:
raise ImportError(
"pyvisa is required for GpibTransport. Install it with: pip install pyvisa"
) from exc
super().__init__(
address=address,
board=board,
timeout=timeout,
use_mav=use_mav,
secondary_address=secondary_address,
poll_time=poll_time,
command_complete_mask=command_complete_mask,
)
self._max_read_chunks = max_read_chunks
self._last_cmd = 0
self.last_stb = 0
@staticmethod
def _serial_send_payload(cmd: str, terminator: str = "\n") -> str:
"""Return a relay-safe serial payload string.
Args:
cmd (str):
Command string to relay.
terminator (str):
Serial command terminator to append (for example ``"\\r\\n"``).
Returns:
(str):
Command with exactly one trailing *terminator* and doubled
double-quotes for safe insertion in a SCPI quoted string.
"""
command = cmd.rstrip("\r\n")
payload = f"{command}{terminator}"
return payload.replace('"', '""')
[docs]
def write(self, data: bytes, slow: int | None = None, host=False) -> None:
"""Write *data* to the 6221 wrapping the data in a SYST:COMM:SER:ESEND command.
Args:
data (bytes):
Raw bytes to transmit. The bytes are decoded as ASCII before
being passed to PyVISA's ``write_raw``.
Keyword Arguments:
slow (int|none, None):
Whether to except the response to be slow and thus to pause for
*slow* milliseconds.
Raises:
ConnectionError:
If the transport is not open.
"""
if self._resource is None:
raise ConnectionError("GPIB transport is not open.")
if isinstance(data, str):
data = data.encode("ascii")
inner = data.rstrip(b"\r\n")
if host:
return super().write(data, slow=slow)
if slow is None:
wrapped = b'SYST:COMM:SER:SEND "' + inner.replace(b'"', b'""') + b';*STB?";ENT?'
else:
wrapped = b'SYST:COMM:SER:SEND "' + inner.replace(b'"', b'""') + b'"'
if perf_counter() - self._last_cmd < _DEFAULT_K6221_SERIAL_POLL * 10000:
sleep(_DEFAULT_K6221_SERIAL_POLL)
self._log_comms_traffic("TX", wrapped)
self._resource.write_raw(wrapped)
self._last_cmd = perf_counter()
if slow is not None:
sleep(slow / 1000)
wrapped = b'SYST:COMM:SER:SEND "*STB?";ENT?'
self._log_comms_traffic("TX", wrapped)
self._resource.write_raw(wrapped)
self.last_stb, response = _get_stb_from_response(self._read_serial_entry_chunk())
self._log_comms_traffic("RX", response)
self._log_comms_traffic("IEEE", f"stb={self.last_stb}")
if self._status_error_mask is not None and self.last_stb & self._status_error_mask:
raise InstrumentError(
f"Bad return status byte from {data.decode()}: STB={self.last_stb}"
)
return self.last_stb
[docs]
def query(self, data: bytes, num_bytes: int | None = None, slow: int | None = False) -> bytes:
"""Perform a write and then read operation in series.
Args:
data (bytes):
Raw bytes to transmit.
Keyword Arguments:
num_bytes (int | None, None):
Optional maximum frame size for this call. When ``None``,
the transport uses the protocol-defined frame-size limit.
slow (int|none, None):
Whether to except the response to be slow and thus to pause for
*slow* milliseconds.
Returns:
(bytes):
The bytes received from the instrument.
Raises:
ConnectionError:
If the transport is not open.
TimeoutError:
If no data is received within :attr:`timeout` seconds.
OSError:
If a low-level I/O error occurs.
"""
if self._resource is None:
raise ConnectionError("GPIB transport is not open.")
if isinstance(data, str):
data = data.encode("ascii")
inner = data.rstrip(b"\r\n")
if slow is None:
wrapped = b'SYST:COMM:SER:SEND "' + inner.replace(b'"', b'""') + b';*STB?";ENT?'
else:
wrapped = b'SYST:COMM:SER:SEND "' + inner.replace(b'"', b'""') + b'"'
if perf_counter() - self._last_cmd < _DEFAULT_K6221_SERIAL_POLL * 10000:
sleep(_DEFAULT_K6221_SERIAL_POLL)
self._log_comms_traffic("TX", wrapped)
self._resource.write_raw(wrapped)
self._last_cmd = perf_counter()
if slow is not None:
sleep(slow / 1000)
wrapped = b"SYST:COMM:SER:ENT?"
self._log_comms_traffic("TX", wrapped)
self._resource.write_raw(wrapped)
response = self._read_serial_entry_chunk()
if slow is not None:
self._resource.write_raw(b'SYST:COMM:SER:SEND "*STB?";ENT?')
rc = self._read_serial_entry_chunk()
response += b";" + rc
self.last_stb, response = _get_stb_from_response(response)
self._log_comms_traffic("RX", response)
self._log_comms_traffic("IEEE", f"stb={self.last_stb}")
if self._status_error_mask is not None and self.last_stb & self._status_error_mask:
raise InstrumentError(
f"Bad return status byte from {data.decode()}: STB={self.last_stb}"
)
return response
def _read_serial_entry_chunk(self, num_bytes: int | None = None) -> bytes:
"""Read a response from 2182A via 6221.
If the response is blank (i.e. just newline) then reissue the ``SYST:COMM:SER:ENT?`` and try again. Repeat
this for 64 times, pausing briefly in between. If we still have a blank response, try sending a ``*STB?`` to
get an error code.
Returns:
(tuple[int,bytes]):
We expect every response to contain a status bytes and a string message (which may be blank).
Raises:
``InstrumentError`` if we can't get a response from the instrument.'
Notes:
The 2182A will send message frames of up to 254 characters and terminate the complete message
with a \n. The 6221 will then append its own \n. So the terminal frame can be recognised as
ending with \n\n. The 2182 resonds with a bare \n if it has no message, so en empty message
is a bare \n\n.
We will leave the processing of possible status bytes to the calling read() method.
"""
command = b"SYST:COMM:SER:ENT?"
accumulated = b""
for _ in range(self._max_read_chunks):
raw = self._resource.read_raw()
if raw in (b"", b"\n", b"\r\n", b"\n\n", b"\r\n\n"):
self._resource.write_raw(command)
sleep(_DEFAULT_K6221_SERIAL_POLL)
continue
if raw.endswith(b"\n\n"):
is_binary = accumulated.startswith(b"#0") or raw.startswith(b"#0")
accumulated += raw[:-2] if is_binary else raw.strip()
self._log_comms_traffic("RX", f"Final message {accumulated}")
return accumulated
self._log_comms_traffic("RX", f"Read frameL {raw}")
is_binary = accumulated.startswith(b"#0") or raw.startswith(b"#0")
accumulated += raw[:-1] if is_binary and raw.endswith(b"\n") else raw.strip()
if num_bytes and len(accumulated) > num_bytes:
accumulated = accumulated[:num_bytes]
raise InstrumentError(f"Overran byte count {num_bytes}; message was {accumulated!r}")
self._resource.write_raw(command)
sleep(_DEFAULT_K6221_SERIAL_POLL)
raise InstrumentError(
f"Incomplete response after {self._max_read_chunks} serial-entry reads: {accumulated}"
)
[docs]
def read(self, num_bytes: int | None = None) -> bytes:
"""Read one response frame from the instrument via the 6221's SYST:COMM:SER:ENT?.
Keyword Arguments:
num_bytes (int | None, None):
Optional maximum frame size for this call. When ``None``,
the transport uses the protocol-defined frame-size limit.
Returns:
(bytes):
Bytes received.
Raises:
ConnectionError:
If the transport is not open.
TimeoutError:
If no data arrives within :attr:`timeout` seconds.
"""
if self._resource is None:
raise ConnectionError("GPIB transport is not open.")
wrapped = b'SYST:COMM:SER:SEND "*STB?";ENT?'
self._log_comms_traffic("TX", wrapped)
self._resource.write_raw(wrapped)
self.last_stb, response = _get_stb_from_response(self._read_serial_entry_chunk())
self._log_comms_traffic("RX", response)
self._log_comms_traffic("IEEE", f"stb={self.last_stb}")
if self._status_error_mask is not None and self.last_stb & self._status_error_mask:
raise InstrumentError(f"Bad return status byte during read: STB={self.last_stb}")
return response
[docs]
def read_status_byte(self) -> int | None:
"""Return the IEEE 488.2 status byte via a wrapped ``*STB?`` query.
Because this is a serial over GPIB transport, this is not an out-of-band operation.
Returns:
(int | None):
The 8-bit status byte, or ``None`` if the transport is not
currently open.
Examples:
>>> from stoner_measurement.instruments.transport import GpibTransport
>>> t = GpibTransport(address=22)
>>> t.read_status_byte() is None # not open
True
"""
if self._resource is None:
return None
return self.last_stb
[docs]
def flush(self) -> None:
"""Send IEEE 488.2 Device Clear to the instrument and reset the interface.
Calls the PyVISA ``clear()`` method, which sends the Selected Device
Clear (SDC) message over the GPIB bus. This resets the instrument's
parser and discards any bytes queued in its output buffer, preventing
stale responses from old commands being misread after a reconnect.
If the resource is not open or Device Clear fails, the exception is
ignored and logged at debug level.
"""
if self._resource is None:
return
import pyvisa
try:
with self.suppress_status_error_check():
self.write(b"*CLS")
except pyvisa.errors.VisaIOError as exc:
logger.debug("Ignoring GPIB Device Clear failure for %s: %s", self.resource_string, exc)