stoner_measurement.instruments.base_instrument.BaseInstrument

class stoner_measurement.instruments.base_instrument.BaseInstrument(transport: BaseTransport, protocol: BaseProtocol, *, auto_check_errors: bool = True)[source]

Bases: ABC

Base class for all instrument drivers.

Uses a composition pattern: each instrument instance holds a transport responsible for the physical byte-level communication, and a protocol responsible for formatting commands and parsing responses. This design allows any transport/protocol combination to be substituted without changing the instrument driver code.

Error checking is performed on demand via check_for_errors() and can be enabled automatically for every write() and query() call by setting auto_check_errors to True.

Two strategies are supported transparently, chosen based on the protocol:

  • Response-embedded (Oxford, Lakeshore) — check_for_errors() inspects the last query response for an inline error token.

  • Error-queue (SCPI) — check_for_errors() polls the instrument’s error queue. If the transport supports an out-of-band status byte (read_status_byte(), e.g. GPIB serial poll), only the ESB bit is checked first to avoid an unnecessary round-trip when no error is pending.

Variables:

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> from stoner_measurement.instruments.protocol import ScpiProtocol
>>> from stoner_measurement.instruments.base_instrument import BaseInstrument
>>> # Second response is consumed by automatic SYST:ERR? polling.
>>> t = NullTransport(
...     responses=[b"ACME,Model1,SN001,v1.0\n", b'+0,"No error"\n']
... )
>>> instr = BaseInstrument(transport=t, protocol=ScpiProtocol())
>>> instr.connect()
>>> instr.is_connected
True
>>> instr.query("*IDN?")
'ACME,Model1,SN001,v1.0'
>>> instr.disconnect()
>>> instr.is_connected
False
check_for_errors(*, command: str | None = None) → None[source]

Poll the instrument for errors and raise if one is found.

The strategy depends on the protocol and transport combination:

  1. If the protocol uses response-embedded errors (errors_in_response is True), this method is a no-op — errors are detected inline by query().

  2. If the transport supports an out-of-band status byte (read_status_byte() returns a non-None value), the IEEE 488.2 Event Status Bit (ESB, bit 2) is checked. If it is clear, no error query is sent.

  3. Otherwise (or if the ESB bit is set) the protocol’s error_query command is sent and check_error() is called on the response.

A reentrant lock (_lock) is held during the error-queue write-read cycle, preventing interleaving with concurrent callers. Because _lock is reentrant, this method is safe to call from within an already-locked write() or query().

Keyword Parameters:

command (str | None) – The command that preceded this check, used to populate the command field of any raised exception. Defaults to None.

Raises:

InstrumentError – If the instrument reports an error.

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> from stoner_measurement.instruments.protocol import ScpiProtocol
>>> from stoner_measurement.instruments.base_instrument import BaseInstrument
>>> t = NullTransport(responses=[b'+0,"No error"\n'])
>>> instr = BaseInstrument(t, ScpiProtocol())
>>> instr.connect()
>>> instr.check_for_errors()   # no exception — queue is clear
>>> instr.disconnect()
clear()[source]

Send the IEEE 488.2 *CLS command.

confirm_identity() → str[source]

Query and validate the identity string against expected tokens.

Returns:

The validated identity string, or an empty string when no expected tokens are configured for this driver.

Return type:

(str)

Raises:

InstrumentError – If configured expected identity tokens are missing from the instrument identity response.

connect() → None[source]

Open the transport connection to the instrument.

After opening the transport, any data accumulated in the transport buffer since the last session is discarded via flush() so that stale responses from previous commands cannot be misread as replies to new queries.

Raises:

ConnectionError – If the underlying transport cannot be opened.

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> from stoner_measurement.instruments.protocol import ScpiProtocol
>>> from stoner_measurement.instruments.base_instrument import BaseInstrument
>>> instr = BaseInstrument(NullTransport(), ScpiProtocol())
>>> instr.connect()
>>> instr.is_connected
True
>>> instr.disconnect()
disconnect() → None[source]

Close the transport connection to the instrument.

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> from stoner_measurement.instruments.protocol import ScpiProtocol
>>> from stoner_measurement.instruments.base_instrument import BaseInstrument
>>> instr = BaseInstrument(NullTransport(), ScpiProtocol())
>>> instr.connect()
>>> instr.disconnect()
>>> instr.is_connected
False
classmethod display_name() → str[source]

Return a human-friendly label for UI driver pickers.

identify() → str[source]

Return the instrument identification string (*IDN?).

Sends the standard IEEE 488.2 *IDN? query and returns the response. Instruments that do not support *IDN? should override this method.

Returns:

Identification string returned by the instrument.

Return type:

(str)

Raises:

ConnectionError – If the transport is not open.

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> from stoner_measurement.instruments.protocol import ScpiProtocol
>>> from stoner_measurement.instruments.base_instrument import BaseInstrument
>>> t = NullTransport(responses=[b"ACME,Model1,SN001,v1.0\n"])
>>> instr = BaseInstrument(t, ScpiProtocol())
>>> instr.connect()
>>> instr.identify()
'ACME,Model1,SN001,v1.0'
>>> instr.disconnect()
property is_connected: bool

True if the underlying transport is currently open.

Returns:

Connection state of the transport.

Return type:

(bool)

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> from stoner_measurement.instruments.protocol import ScpiProtocol
>>> from stoner_measurement.instruments.base_instrument import BaseInstrument
>>> instr = BaseInstrument(NullTransport(), ScpiProtocol())
>>> instr.is_connected
False
query(command: str, slow: int | None = None) → str[source]

Send a query and return the instrument’s response.

Combines write() and read() into a single call. The query is formatted by protocol before transmission.

If auto_check_errors is True:

  • For protocols with response-embedded errors (Oxford, Lakeshore), check_error() is called on the parsed response directly.

  • For error-queue protocols (SCPI), check_for_errors() is called after the response is returned.

A reentrant lock (_lock) is held for the entire write-read cycle (including any error check) so that two concurrent callers cannot interleave their write/read sequences on the same instrument.

Parameters:

command (str) – Query string in the instrument’s command language.

Keyword Arguments:

slow (int|none, None) – Whether to except the response to be slow and thus to pause for slow milliseconds.

Returns:

Parsed response string.

Return type:

(str)

Raises:
  • ConnectionError – If the transport is not open.

  • TimeoutError – If no response is received within the transport timeout.

  • InstrumentError – If auto_check_errors is True and the instrument signals an error.

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> from stoner_measurement.instruments.protocol import ScpiProtocol
>>> from stoner_measurement.instruments.base_instrument import BaseInstrument
>>> t = NullTransport(responses=[b"ACME,1,SN,v1\n"])
>>> instr = BaseInstrument(t, ScpiProtocol())
>>> instr.connect()
>>> instr.query("*IDN?")
'ACME,1,SN,v1'
>>> instr.disconnect()
query_ieee_block(command: str, *, max_payload: int = 268435456) → bytes[source]

Send a query and return its IEEE 488.2 definite-length block payload.

The complete write/read/error-check cycle is protected by the instrument lock. Response chunks are accumulated until the advertised payload and protocol terminator have been received, so embedded newline bytes do not truncate binary data.

Parameters:

command (str) – Query string in the instrument’s command language.

Keyword Parameters:

max_payload (int) – Safety limit for the advertised payload length. Defaults to 256 MiB.

Returns:

The block payload without its header or trailing terminator.

Return type:

(bytes)

Raises:
  • ValueError – If the block header, length, terminator, or trailing data is malformed.

  • TimeoutError – If the transport stops returning data before the block is complete.

read(*, command: str | None = None) → str[source]

Read a response from the instrument.

Reads raw bytes from the transport and parses them using protocol. Any protocol-specific response framing (for example, terminator handling) is delegated to the transport layer.

Keyword Parameters:

command (str | None) – Command/query string that produced this response, when known. Passed to parse_response(). Defaults to None.

Returns:

Parsed response string.

Return type:

(str)

Raises:

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> from stoner_measurement.instruments.protocol import ScpiProtocol
>>> from stoner_measurement.instruments.base_instrument import BaseInstrument
>>> t = NullTransport(responses=[b"+1.234\n"])
>>> instr = BaseInstrument(t, ScpiProtocol())
>>> instr.connect()
>>> instr.read()
'+1.234'
>>> instr.disconnect()
read_status_byte() → int | None[source]

Return the instrument status byte via an out-of-band mechanism.

Some transports (notably GPIB) can perform a serial poll to read the IEEE 488.2 status byte (STB) without sending a command, allowing the caller to check whether an error condition exists before issuing an expensive error-queue query.

The default implementation returns None, indicating that no out-of-band mechanism is available. Subclasses that support hardware-level status polling (e.g. GpibTransport) should override this method.

If read_status_byte() returns None, check_for_errors() will fall back to issuing the protocol’s error_query command directly.

Returns:

The 8-bit status byte, or None if not supported.

Return type:

(int | None)

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> NullTransport().read_status_byte() is None
True
reset() → None[source]

Send the standard IEEE 488.2 reset command (*RST).

Instruments that do not support *RST should override this method.

Raises:

ConnectionError – If the transport is not open.

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> from stoner_measurement.instruments.protocol import ScpiProtocol
>>> from stoner_measurement.instruments.base_instrument import BaseInstrument
>>> t = NullTransport()
>>> instr = BaseInstrument(t, ScpiProtocol())
>>> instr.connect()
>>> instr.reset()
>>> t.write_log
[b'*RST\n']
>>> instr.disconnect()
write(command: str, slow: int | None = None) → None[source]

Send a command and consume any protocol-required acknowledgement.

The command is formatted by protocol before being passed to transport. If auto_check_errors is True and the protocol uses an error queue (not response-embedded errors), check_for_errors() is called after the command is sent.

Protocol-required acknowledgements are always consumed and validated, including when auto_check_errors is disabled. Missing replies propagate the transport timeout; actions are not automatically retried.

A reentrant lock (_lock) is held for the entire write and optional error-check cycle so that two concurrent callers cannot interleave their write/read sequences on the same instrument.

Parameters:

command (str) – Command string in the instrument’s command language.

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.

  • TimeoutError – If a required acknowledgement does not arrive in time.

  • InstrumentError – If a required acknowledgement is invalid, or enabled error polling reports an error after processing the command.

Examples

>>> from stoner_measurement.instruments.transport import NullTransport
>>> from stoner_measurement.instruments.protocol import ScpiProtocol
>>> from stoner_measurement.instruments.base_instrument import BaseInstrument
>>> t = NullTransport()
>>> instr = BaseInstrument(t, ScpiProtocol())
>>> instr.connect()
>>> instr.write("OUTP ON")
>>> t.write_log
[b'OUTP ON\n']
>>> instr.disconnect()