Writing a plugin¶
A plugin teaches Benchloom an instrument. It is a folder with a plugin.toml
and Python files: a driver that talks to the instrument, and usually a
simulator that answers like it, so tests can be written without hardware.
From the driver's commands, Benchloom makes the Lua functions, the nodes of
the node editor and the entries in the Devices panel.
The built-in demo plugin is the reference example, and the other built-in plugins show real instruments: SCPI over GPIB, Modbus over RS-485, a binary USB protocol.
A first plugin¶
acme/
├── plugin.toml
├── driver.py
└── simulator.py
plugin.toml
[plugin]
id = "acme" # unique; device types become acme.<device id>
name = "ACME instruments"
version = "1.0.0"
description = "ACME bench supplies."
[[device]]
id = "ps3005"
name = "ACME PS-3005 power supply"
description = "30 V / 5 A bench supply, SCPI over USB serial."
driver = "driver:Ps3005" # module:class, relative to the plugin folder
simulator = "simulator:Ps3005Sim"
transports = ["serial", "sim"]
default_name = "psu" # suggested name in a project
default_resource = "serial://COM3?baud=9600"
driver.py
from benchloom import Param, ScpiDevice, command
class Ps3005(ScpiDevice):
@command("Set the output voltage", params={"volts": Param(unit="V", min=0, max=30)})
def set_voltage(self, volts: float) -> None:
self.send(f"VOLT {volts:.3f}")
@command("Switch the output on or off")
def set_output(self, on: bool) -> None:
self.send("OUTP ON" if on else "OUTP OFF")
@command("Measure the output voltage", unit="V")
def measure_voltage(self) -> float:
return self.ask_number("MEAS:VOLT?")
def close(self) -> None:
if not self.leave_output_on():
self.send("OUTP OFF") # a source switches its output off after a test
simulator.py
from benchloom.scpi import ScpiSimulator, sim_bool, sim_number
class Ps3005Sim(ScpiSimulator):
identity = "ACME,PS-3005,SIM,1.0"
def reset(self) -> None:
self.volts, self.on = 0.0, False
def routes(self):
return [
(r"VOLT", self._set_volts),
(r"OUTP", self._set_output),
(r"MEAS:VOLT\?", lambda arg: f"{self.volts if self.on else 0.0:.3f}"),
]
def _set_volts(self, arg):
self.volts = sim_number(arg, 0, 30)
def _set_output(self, arg):
self.on = sim_bool(arg)
Put the acme folder into Benchloom with Plugins → Install from folder…
(or benchloom plugins install acme), add the device with resource sim://,
and a script can use it:
psu:set_voltage(5)
psu:set_output(true)
print(psu:measure_voltage())
The manifest¶
| Key | Under | Meaning |
|---|---|---|
id |
[plugin] |
the plugin's id, a short lower-case name; must be unique |
name, version, description |
[plugin] |
shown in the plugin manager |
manufacturer |
[plugin] |
optional: the maker of its devices, such as "HP"; the Add device dialog groups devices by it (the plugin's name if left out) |
version |
[plugin] |
raise it with every change users get: the last number for fixes, the middle one for new devices or commands |
id |
[[device]] |
the device's id; the device type is <plugin id>.<device id> |
name, description |
[[device]] |
shown in the Add device dialog, and searched by it |
category |
[[device]] |
optional: the kind of device, for the dialog's kind filter (see below) |
manufacturer |
[[device]] |
optional: overrides the plugin's manufacturer for this device |
driver |
[[device]] |
module:Class of the driver |
simulator |
[[device]] |
module:Class of the simulator, used for sim:// |
transports |
[[device]] |
the connections it supports, such as ["serial", "tcp", "visa", "sim"] |
default_name, default_resource |
[[device]] |
offered when the device is added |
tested |
[[device]] |
whether the driver was tried on a real instrument: yes, partly or no, then optionally : and what was tried or is missing, e.g. "partly: a 53131A; the 53132A not yet". Shown as "Tried on hardware" in the Add device dialog, the plugin manager and benchloom describe; "Not stated" when left out |
Kind and manufacturer¶
The Add device dialog lists device types by manufacturer and can show only
one kind of device. Give each device its kind in category:
category |
Shown as |
|---|---|
dmm |
Multimeter |
scope |
Oscilloscope |
psu |
Power supply |
load |
Electronic load |
generator |
Signal generator |
counter |
Counter |
ac_source |
AC source |
smu |
Source measure unit |
analyzer |
Analyzer |
lcr |
LCR meter |
other |
Other |
Another word works too and becomes a kind of its own (the built-in plugins use
data_acquisition for the 34970A and transfer_standard for the Wavetek 4950;
spectrum_analyzer is shown as "Spectrum analyzer"). A device without a category counts as Other,
and one without a manufacturer is listed under the plugin's name, so older
plugins keep working unchanged.
Give the name the device carries: "HP", "Agilent" or "Keysight" are all
right for the company that changed its name from one to the next, and the
dialog lists all three (and "Hewlett-Packard") in one group, HP / Agilent /
Keysight, while the device's details still show the name you gave.
[plugin]
id = "acme"
name = "ACME instruments"
manufacturer = "ACME"
[[device]]
id = "ps3005"
name = "ACME PS-3005 power supply"
category = "psu"
Settings¶
A device can declare settings, such as a bus address. The Add device dialog
shows them as fields, they are saved in the project's device entry, and the
driver reads them from self.settings:
[[device.setting]]
name = "address"
label = "Modbus address"
type = "int" # int, float, bool or text
default = 1
min = 1
max = 247
help = "Set on the instrument."
address = self.settings.get("address", 1)
Discovery¶
Find devices recognizes a device type by what its [device.discovery]
table declares. Everything is optional. Declare only what the manual (or the
instrument on your bench) shows, and nothing that changes the instrument:
[device.discovery]
usb = ["049F:505A"] # USB ids, seen without opening the device
talk = '^[+-][0-9.]+E[+-][0-9]$' # GPIB: the line it sends unasked when addressed to talk
idn = '34420A' # its reply to *IDN?
serial = { baud = 115200, stopbits = 2, query = "UMO", reply = '^FY(6900|6800)' }
listen = { baud = 2400, dtr = true, rts = false, recognize = "meter:recognize" }
For a binary protocol, serial gives a fixed frame in hex instead of a text
query, and a function that checks the reply. The Kunkin KP184 declares a Modbus
read of its input state at address 1:
serial = { baud = 9600, query_hex = "01 03 01 0E 00 04 24 36", recognize = "driver:recognize" }
The frame is sent as it is, so it carries its own checksum. recognize gets
the bytes that came back within half a second, with an echo of the frame (some
RS-485 adapters send one) already removed.
Patterns are regular expressions, searched in the reply. A default_resource
starting with usb:// counts as a usb id by itself. serial is a query sent
(with a line feed) to serial ports the user ticks; its settings may also give
bytesize and parity. Every plugin's query goes to every ticked port that
nothing recognized before it, so a serial query must be harmless to any
device: a read-only query, never one that sets something. For Modbus that means
function 3 or 4 (read), never 5, 6, 15 or 16 (write), and never address 0, the
broadcast every device on the bus acts on. listen sends
nothing; recognize names a function that gets the bytes heard and returns
whether they are this device's. 1200 baud is refused: it starts the
bootloader of some Arduino boards.
A *IDN? reply that fits no idn pattern still matches a device type whose
name contains the reply's model number (53131A).
Commands¶
A driver is a class derived from Device, or from ScpiDevice for SCPI
instruments. Every method marked with @command becomes a command:
@command("Set the current limit", params={"amps": Param(unit="A", min=0, max=5)})
def set_current_limit(self, amps: float) -> None: ...
@command("Measure the output current", unit="A") # unit of the result
def measure_current(self) -> float: ...
@command("Select the input", params={"source": Param(choices=("front", "rear"))})
def set_input(self, source: str = "front") -> None: ... # optional, with a default
- Types come from the annotations:
float(a number),int,bool,str,list. Benchloom checks and converts every argument before the method runs, so a script passing text for a number, or 40 V to a 30 V supply, stops with a clear error at its own line, and nothing is sent. Numbers must be finite:nan(from0/0) andmath.hugeare refused.list[float](orlist[int],list[str], ...) checks each item as well; a barelisttakes items of any type. Paramaddsunit,min,max,choicesanddocto an argument. On alistargument,min,maxandchoicesapply to each item.- Results can be numbers, texts, booleans, lists and dicts; lists and dicts
become Lua tables. A scope's waveform is a dict
{"time": [...], "volts": [...]}, whichsave_waveformunderstands. - The first line of the docstring is used when the decorator has no text.
Models: one driver, several limits¶
Instrument families often share one command set and differ only in their ratings, like the HP 6632A, 6633A and 6634A. Write one driver with a table of models, and let the commands name the limits instead of giving numbers:
from dataclasses import dataclass
@dataclass(frozen=True)
class Ratings:
max_volts: float
max_amps: float
class Psu(Device):
MODELS = {"PS-3005": Ratings(30.0, 5.0), "PS-6003": Ratings(60.0, 3.0)}
model = "PS-3005" # used when the class is created directly, as in tests
@command("Set the current limit (up to {max_amps:g} A on the {model})",
params={"amps": Param(unit="A", min=0, max="max_amps")})
def set_current_limit(self, amps: float) -> None:
self.transport.write(f"ISET {amps:.3f}")
def connect(self) -> None:
if self.model not in self.transport.query("*IDN?"):
raise CommandError(f"this is not a {self.model}")
- A
minormaxthat is a text names a field of the model's ratings (a dataclass or a dict);{field}and{model}in a command's text are filled in the same way. self.modelis the model in use,self.ratingsits ratings.- A simulator can have the same
MODELSandmodel: it is made per model too. model_variant(Psu, "PS-6003")gives the class for one model, e.g. in tests.
In plugin.toml, one [[device]] entry holds what the models share, with a
[[device.model]] for each model. Each becomes a device type of its own, with
its own id in projects:
[[device]]
driver = "psu:Psu"
simulator = "psu:PsuSim"
transports = ["serial", "sim"]
category = "psu"
description = "Programmable supply, {rating}, with a serial port."
[[device.setting]] # shared by all models
name = "check_errors"
type = "bool"
default = true
[[device.model]]
id = "ps3005" # the device id: acme.ps3005
model = "PS-3005" # the key in the driver's MODELS
name = "ACME PS-3005"
rating = "30 V / 5 A" # any text key, for {rating} in the description
tested = "yes: on a PS-3005"
[device.model.discovery] # only this model's
idn = 'PS-3005'
[[device.model]]
id = "ps6003"
model = "PS-6003"
name = "ACME PS-6003"
rating = "60 V / 3 A"
tested = "no: written from the manual"
A model can set any key of the device entry (name, description, tested,
discovery, default_resource, ...); what it leaves out comes from the
[[device]] entry. Without [[device.model]] an entry is one device type, as
before.
Talking to the instrument¶
self.transport is the open connection:
| Method | Does |
|---|---|
write(text) |
sends a line, with the write terminator |
read() |
reads a line |
query(text) |
writes, then reads the reply |
write_raw(data), read_raw(size), read_until(term) |
bytes, for binary protocols |
clear_input() |
drops anything unread |
set_timeout(seconds) |
for one slow command |
device_clear() |
the GPIB/USBTMC device clear, which aborts a measurement in progress; does nothing on serial and TCP |
read_to_line_end() |
Prologix/AR488 only: end reads at the line feed instead of EOI, for instruments that never send EOI; check with hasattr(self.transport, "read_to_line_end") |
ScpiDevice adds send(text) (write, then ask SYST:ERR? so a rejected
command fails at once), ask(text) and ask_number(text), and gives every
SCPI driver the commands idn, reset, clear, get_error, write,
query and query_number.
Life of a device¶
- The transport is opened, then the driver is created with it and its
settings, and
connect()is called: the place to check the instrument answers or to set a known state. - The test calls commands.
- When the test ends, also by an error or Stop,
close()is called. A driver of anything with an output switches it off here, unlessself.leave_output_on()is true (the project asked for it).
identify() returns a short text for Test connection; by default it calls
idn when the driver has it.
Simulators¶
A simulator is a transport that answers like the instrument. With it, tests of your driver need no hardware, and users can write a test before the instrument arrives.
ScpiSimulator(frombenchloom.scpi): list(pattern, handler)pairs inroutes().*IDN?,*RST,*CLSandSYST:ERR?work out of the box, and unknown commands or bad values are queued as SCPI errors, as on a real instrument.sim_number(arg, low, high)andsim_bool(arg)check arguments that way.SimTransport: implementhandle(line)for any line-based protocol; return the reply text,Nonefor no reply, orbytessent as they are.RawSimTransport: implementhandle_bytes(data)for binary protocols.
A sim:// resource can pass options to the simulator: sim://?load_ohms=5
creates it with load_ohms="5", as text. Take your options out before the
rest goes to the base class, which refuses options it does not know:
def __init__(self, load_ohms="10", **options):
super().__init__(**options)
self.load_ohms = float(load_ohms)
Testing¶
from pathlib import Path
import pytest
from benchloom.engine import open_device
from benchloom.plugin import PluginRegistry
from benchloom.project import DeviceConfig
PLUGINS = PluginRegistry([Path(__file__).parent.parent]) # the folder holding acme/
def test_set_and_measure():
psu = open_device(PLUGINS, DeviceConfig("psu", "acme.ps3005", "sim://"))
psu.call("set_voltage", 5)
psu.call("set_output", True)
assert psu.call("measure_voltage") == pytest.approx(5)
with pytest.raises(Exception, match="maximum"):
psu.call("set_voltage", 40)
call runs a command the way a script does, with the same checks.
Try it on real hardware
A simulator written from the same manual as the driver will agree with it even where both misread the manual. Before sharing a plugin, run it on the instrument once, and say in its description what was tried.
Sharing it¶
- With a project: put the plugin folder into the project's
plugins/folder. It travels with the project; others are asked before it loads. - As a .zip: zip the folder; others use Install from .zip….
- In the plugin registry: others find it under Browse online. See The plugin registry.
- In Benchloom itself: for widely used instruments, a pull request is welcome; see CONTRIBUTING.md.
A plugin is Python code and runs with the user's rights. Benchloom does not sandbox plugins the way it does Lua scripts.