Driver Programming

From SweepMe! Wiki
Jump to navigation Jump to search

Drivers are small Python-based code snippets that define how SweepMe! should interact with different instruments. Driver programming in SweepMe! refers to the process of creating new drivers or enhancing the capabilities of existing ones. The drivers are open-source and can be found on the instrument-drivers GitHub repository.

The complete rules for writing a driver are in the driver guide of the repository: DRIVER_GUIDE.md. It covers the files, the GUI parameters, the sequencer lifecycle, the ports, the communication commands with the Driver API (@command), code style, checklists, testing and contributing, and ends with a complete example driver. It is written for humans and AI agents. This page gives the overview, the starting points and the steps inside SweepMe!, and links each topic to the guide.

Core principles

  • Instruments become functional units. SweepMe! abstracts an instrument into the features a module needs. A multifunction instrument gets one driver per capability, e.g. one for the Signal module and one for the Scope module, so that each can be used independently.
  • A driver is a class Device(EmptyDevice) in a file main.py. EmptyDevice comes from the Python package pysweepme and defines the semantic functions connect(), initialize(), configure(), apply(), measure(), call(), ... that SweepMe! calls in the order of the Sequencer procedure. Every function is optional; the driver fills the ones it needs with the commands of its instrument.
  • Each instrument command lives in a communication command, a public method such as set_voltage or get_voltage that the semantic functions call. Declared with @command, these methods are checked by SweepMe! and are what pysweepme scripts, Instrument Control and AI agents use (see below).
  • A driver returns data through call(): as many values as it names in self.variables and self.units, which SweepMe! plots, shows and saves.

Getting started

Choosing your starting point

  • New driver: Start from the smallest driver of the driver guide (four lines of code) and extend it, or copy one of the Simulation drivers that come with SweepMe! (Switch-Simulation_Driver is the shortest, SMU-Simulation_Diode and Temperature-Simulation_Driver are complete examples). They declare their communication commands and are the reference examples for the Driver API. The complete example driver of the guide shows every part of a driver in one file.
  • A similar driver exists: Find it in the Version manager or the repository, create a custom version and rename it, and adapt it.
  • Templates: The minimal logger template and the full template list almost all functions of a driver with comments. They predate the Driver API: they use the legacy GUI functions and declare no commands.

Where SweepMe! finds your driver

  • Custom version: the Version manager (Tools → Version Manager) creates an editable copy of any driver in the public folder CustomDevices (right-click a version → Create custom version or Create new driver). Changes take effect with the next run, no restart needed.
  • Repository: set the environment variable SWEEPME_DRIVERS_REPO to the src folder of a local clone of the instrument-drivers repository and restart SweepMe!; its drivers are listed with the origin "repo". See Drivers.
  • Reloading GUI fields: after changing the GUI parameters of a driver, click the driver selection box of the module to rebuild its GUI. Changed defaults or dropdown options appear after re-selecting the option or recreating the module.

Development steps

  1. Import EmptyDevice from pysweepme.EmptyDeviceClass, and command and the markers from pysweepme.commands.
  2. Define the class Device(EmptyDevice). In __init__, call super().__init__(), set self.shortname, the return variables and units, and the port settings (self.port_manager, self.port_types). Keep __init__ light: the instance is created often. Do not add a description attribute; the documentation belongs into doc/description.md.
  3. Add update_gui_parameters (returns the GUI fields with defaults) and apply_gui_parameters (receives the selection, always with parameters.get(key, default)).
  4. Implement the semantic functions you need, in pairs and in this order: connect/disconnect, initialize/deinitialize, configure/unconfigure (reconfigure right after), poweron/poweroff, signin/signout, then the measurement-point functions start, apply, reach, adapt, measure, request_result, read_result, process_data, call, finish. When SweepMe! calls which function is described on Sequencer procedure.
  5. Write the communication commands, one method per instrument command, and declare them with @command.
  6. Add helper functions at the end.
  7. Write doc/description.md, run tools/check_driver.py of the repository, and test the driver (see below).

The Driver API: communication commands

@command needs SweepMe! 1.6.1.9 or later (pysweepme 1.6.1.5). Type hints, Literal choices and docstrings work with every version.

A communication command sends exactly one command of the instrument and reads its answer, if there is one. With the Driver API of pysweepme, the driver declares what a command takes and answers, with standard Python annotations and the decorator @command from pysweepme.commands. The signature tells the kind of command: a set command takes a value and returns nothing, a read command returns the value it reads, a run command such as reset() executes something, takes no value and returns nothing. Literal declares fixed choices, Annotated with Unit, Label and Range adds unit, display text and bounds, Selector() marks the parameter that addresses a channel or another part of the instrument, and returns= names the quantity a read command answers.

from typing import Annotated

from pysweepme.commands import Range, Selector, Unit, command
from pysweepme.EmptyDeviceClass import EmptyDevice

Channel = Annotated[int, Selector(), Range(1, 2)]
Volts = Annotated[float, Unit("V")]


class Device(EmptyDevice):

    def apply(self) -> None:
        self.set_voltage(self.channel, float(self.value))

    @command
    def set_voltage(self, channel: Channel, voltage: Annotated[Volts, Range(-20.0, 20.0)]) -> None:
        """Set the output voltage."""
        self.port.write(f"SOUR{channel}:VOLT {voltage}")

    @command(returns=("voltage",))
    def get_voltage(self, channel: Channel) -> Volts:
        """Measure the voltage."""
        return float(self.port.query(f"MEAS{channel}:VOLT?"))

SweepMe! checks every call of a declared command against its declaration, whoever calls it, and refuses a value outside the declared choices or range. Declare only what the manual or a test on the instrument confirms: a wrong Range blocks a valid value, a missing declaration costs nothing. Every level is optional: a driver with only the semantic functions it needs is still a valid driver and welcome in the repository. Declared commands make it usable from scripts, in the Control tab of Instrument Control and by AI agents without guessing. All rules, markers and naming conventions: section 7 of the driver guide.

Where to find what

The driver guide is the reference. The wiki pages in the right column add the SweepMe! side: the user interface, the folders and the per-function pages.

Topic Driver guide Wiki
Files and folders of a driver, config.ini, libraries/ Section 2 Drivers, External libraries and dependencies, Folder system
The Device class, __init__, return variables Section 3 Measurement value, Idle value
GUI parameters, reserved keys, sweep modes, calibration files Section 4 Modules, Parameter system
The sequencer lifecycle: what belongs into which function, reconfigure, threads, actions Section 5 Sequencer procedure and the pages of the functions, e.g. connect(), reconfigure(), call()
Ports: port manager, port properties, timeouts, several instances on one port, SCPI, GPIB adapters Section 6 Port manager, Supported ports, Protocols, Unblocking parallelization
Communication commands and the Driver API Section 7 pysweepme, Instrument Control
Messages to the user, errors, folders, machine-specific configuration Section 8 Configuration File, Debugging
Working from manuals, instrument behaviour that bites Section 9
Code style, order within main.py, naming Section 10
Checklists Section 11
Third-party libraries, Python versions, migration to Python 3.14 Section 12 External libraries and dependencies, Migration guide
Testing and debugging Section 13 pysweepme, Instrument Control, Debugging
Contributing, licenses Section 14 Drivers, License Guide for Drivers
A complete example driver Section 15 Simulation drivers
Arduino Arduino Driver guide

Notes on the SweepMe! side

  • Compatibility with SweepMe! 1.6: from version 1.6.1, SweepMe! runs on Python 3.14 (64 bit); compiled libraries need a libraries/libs_314_64 folder, imp.load_source is replaced by from pysweepme import load_source, and SweepMe! 1.6.1.9 adds the Driver API, which a driver that imports pysweepme.commands needs. All other drivers are not affected. See Migration guide.
  • Configuration file:' a driver that needs a setup-specific .ini file ships a template with the name of the driver. The user copies it to the public folder CustomFiles via the right-click menu of the version in the Version manager (Copy configuration (.ini) file to 'CustomFiles) and edits it there. See Configuration File.
  • Calibrations: modules such as Spectrometer and NetworkAnalyzer have a button Find calibrations that fills the Calibration field from the public folder CalibrationFiles in one of the three ways described in section 4.4 of the guide.
  • Module-specific functions: some modules call further functions of the driver, e.g. the Monochromator module for a home position. They are described on the page of each module.
  • Documentation: doc/description.md is shown in SweepMe! behind the help icon next to the driver selection, and on the driver's page at sweep-me.net/devices once it is released.

Testing and contributing

  • In SweepMe!: use a custom version or the repository (see above), build a sequence with the module, run it, and watch the Debug widget and the port terminal. A driver that does not load, e.g. because of a wrong @command declaration, is reported in the debug log and at the start of a run.
  • With pysweepme: load the driver with pysweepme.get_driver in a Python script (same Python version as SweepMe!, 3.14 for 1.6.1) and run it through its lifecycle and its communication commands. See pysweepme.
  • With Instrument Control (SweepMe! Pro, 1.6.1.9 or later): put the driver on a bench and call every command yourself in the Control tab, or let an AI agent do it. Every value outside a declaration or a bench limit is refused. This is the recommended way to test a driver with declared commands. See Instrument Control.
  • check_driver.py: python tools/check_driver.py src/<DriverFolder> in the repository lists where a driver departs from the rules of the guide, e.g. a command without type annotations or docstring, a set command that returns a value, or a description attribute. The list is a work list; a driver stays valid with any finding.
  • Contributing: go through the checklists of the guide, then open a pull request to the instrument-drivers repository or send the driver to contact@sweep-me.net. A contribution agreement is needed before pull requests can be accepted; drivers are published under the MIT license whenever possible. Say what was tested on hardware and what was not. See Drivers and the License Guide for Drivers.