stoner_measurement.instruments.base_instrument.BaseInstrument¶
- class stoner_measurement.instruments.base_instrument.BaseInstrument(transport: BaseTransport, protocol: BaseProtocol, *, auto_check_errors: bool = True)[source]¶
Bases:
ABCBase 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 everywrite()andquery()call by settingauto_check_errorstoTrue.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:
transport (BaseTransport) – Transport layer instance (serial, Ethernet, GPIB, …).
protocol (BaseProtocol) – Protocol instance (SCPI, Oxford, Lakeshore, …).
auto_check_errors (bool) – When
True,write()andquery()automatically callcheck_for_errors()after each operation. Defaults toTrue.
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:
If the protocol uses response-embedded errors (
errors_in_responseisTrue), this method is a no-op — errors are detected inline byquery().If the transport supports an out-of-band status byte (
read_status_byte()returns a non-Nonevalue), the IEEE 488.2 Event Status Bit (ESB, bit 2) is checked. If it is clear, no error query is sent.Otherwise (or if the ESB bit is set) the protocol’s
error_querycommand is sent andcheck_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_lockis reentrant, this method is safe to call from within an already-lockedwrite()orquery().- Keyword Parameters:
command (str | None) – The command that preceded this check, used to populate the
commandfield of any raised exception. Defaults toNone.- 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()
- 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
- 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¶
Trueif 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()andread()into a single call. The query is formatted byprotocolbefore transmission.If
auto_check_errorsisTrue: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_errorsisTrueand 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 toNone.- Returns:
Parsed response string.
- Return type:
(str)
- Raises:
ConnectionError – If the transport is not open.
TimeoutError – If no data is received within the transport timeout.
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()returnsNone,check_for_errors()will fall back to issuing the protocol’serror_querycommand directly.- Returns:
The 8-bit status byte, or
Noneif 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
*RSTshould 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
protocolbefore being passed totransport. Ifauto_check_errorsisTrueand 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_errorsis 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()