Write a device
A device is a Python class. LabOrchestra runs it in a process of its own, shows it on the dashboard, and makes it available to scripts. You write what is specific to your instrument: how to open it, how to read it, and what it can do. This page takes the file that New Python driver… made and turns it into a real driver. The rules in short form are in the device contract.
Show it in the Add device list
Section titled “Show it in the Add device list”A driver that others may use can say what it is. Two comment lines right after the # /// script block of the file give the name a person looks for and a short category:
# title: Thorlabs Elliptec stages# category: motioncategory |
Shown as |
|---|---|
oscilloscope |
Oscilloscopes and digitizers |
source |
Signal sources (RF, function, pulse generators) |
optics |
Lasers and optics |
imaging |
Cameras and spectrometers |
motion |
Positioners and motion |
vacuum |
Vacuum |
environment |
Temperature and environment |
electrical |
Electrical measurement (multimeters, source-measure units, lock-ins, counters) |
power |
Power supplies and magnets |
io |
Digital I/O and infrastructure |
other |
Other |
Another word works too and gets a group of its own, but a word from the table keeps the list tidy for everyone.
The four parts
Section titled “The four parts”from laborchestra import Device, action
class PowerMeter(Device): """A laser power meter on a serial port."""
# 1. options: what you set for each device on the Devices page port: str # no default: required baudrate: int = 9600 # a default: optional simulate = False # every driver has this one
# 2. state: what everyone sees, live, and what is recorded state = {"simulated": False, "power": None, "status": "starting"}
# 3. how the device starts, runs and stops def connect(self): self.state["simulated"] = self.simulate if not self.simulate: import serial self.meter = serial.Serial(self.port, self.baudrate, timeout=1)
def run(self): while self.running: self.state["power"] = self._read() self.state["status"] = "ok" self.sleep(1.0)
def close(self): if not self.simulate: self.meter.close()
# 4. actions: what dashboard, scripts and other devices can ask for @action def set_wavelength(self, nanometers: float): """Tells the meter which wavelength to correct for.""" with self.lock: self.meter.write(f"WAV {nanometers}\n".encode())Options are class attributes. One with a type but no default is required; one with a default is optional. The Devices page makes a form of them, with checks, and the values go into devices.json.
state is a dictionary. Whatever you change in it, also nested (self.state["channels"][0]["power"] = 3), is sent to every dashboard and script, recorded when it changes, and kept in the history for traces. You never send anything yourself. Keys are snake_case.
connect() opens the instrument. Raise an exception to say why the device cannot start: it is shown as the device’s error, and LabOrchestra tries again after a pause. run() is the loop that reads the instrument. It runs until the device is stopped; use self.running as the condition and self.sleep(seconds) instead of time.sleep, so that stopping is quick. async def run works too. close() releases the instrument.
Actions are the methods marked @action. Their type hints are checked, and they make the forms and the documentation of the device. When an action returns, its effects are already in state, so a script that sets a value and then reads it sees the new value.
Names that are taken
Section titled “Names that are taken”id, lock and the framework’s own underscore names (_stop, _lab) belong to LabOrchestra: assigning one raises an error that names it (and do not replace self.log). Give your own attributes a word of your driver (_serial_port, _stop_flags).
Rules that save you trouble
Section titled “Rules that save you trouble”- Read errors are not hidden. If a reading fails, put
Noneinto the state and say why in astatusfield. Never write0for “no value”: a recording of zeros looks like a measurement. - Actions run at the same time (in parallel threads), so that a
stopcan reach a device in the middle of a long move. When two accesses to the instrument must not overlap, usewith self.lock:. Keep the lock for the access, not for a long wait. - Simulation is an option, never a silent fallback. Offer
simulate, putsimulated: Trueinto the state when it is on, and raise an error that says what to set when the port is missing. People should never record simulated data by accident. - Write the limits of the instrument down. A bus that times out when it is asked too often gets its polling interval, its retries and its timeouts in the docstring.
- Do not crash to survive. An error in
runis logged, shown on the dashboard, and the device restarts with growing pauses. You need notry/exceptfor that, only where you can do something useful about the error. - Stop quickly. Use short timeouts on reads, so that
self.runningis checked often.
Talk to the instrument: sockets, serial, VISA
Section titled “Talk to the instrument: sockets, serial, VISA”laborchestra.transport has one small interface for the three usual links, with no dependencies for TCP:
from laborchestra.transport import Scpi, Tcp # also Serial(port, baudrate) and Visa(resource)
def connect(self): self.scpi = Scpi(Tcp(self.host, self.tcp_port)).open() self.state["identity"] = self.scpi.idn()
@actiondef set_frequency(self, channel: int, frequency: float): with self.lock: self.scpi.write(f"FREQ {frequency!r}") self.scpi.check_errors("FREQ") # the instrument's own error queue, as a ValueError for the callerquery, query_float, write, opc(), idn() and check_errors() are there; one message is in flight at a time. A reply that does not come in time raises TransportTimeout (a TimeoutError), a closed or refused link ConnectionLost (a ConnectionError). Use a plain Tcp socket (port 5025) where the instrument has one; Visa needs pyvisa in the device’s dependencies. laborchestra.testing.FakeScpiServer is a fake instrument on a real socket, so simulate = True takes the same path as hardware (see drivers/scpi_frequency_generator.py).
When the instrument goes away
Section titled “When the instrument goes away”A cable pulled or an instrument switched off is a property of the device, not of each value. Raise ConnectionError or TimeoutError (the transport does) in run() or in connect() (an instrument that is off when the device starts is offline too; any other exception in connect() is a startup error): the device is shown as offline with the reason, its values keep what they were, actions are refused with “Device is offline: …”, and LabOrchestra calls close() and connect() again with growing pauses (1 s up to 30 s) and then run() again. You may also call self.offline("reason") and self.online() yourself. Profile values stay numbers, so you do not need None for a lost connection; a per-channel status is for instruments that report a failure of one channel (a gauge with one unplugged sensor).
Use other devices
Section titled “Use other devices”A device can read and call the others:
pressure = self.lab["pressure"].state["channels"][1]["pressure"] # no round trip: pushed to youself.lab["turbo"].start(0) # returns when the pump has startedself.lab["stage"].wait_for(lambda s: s["channels"][0]["actual_position"] > 40)wait_ready() waits until another device is running, which is useful when a device depends on one that starts later.
Remember values over a restart
Section titled “Remember values over a restart”List the state keys that should survive in persist:
persist = ["wavelength"]The key must already be in the initial state (as None if you like), or the device does not start. They are saved when they change and restored at the next start. Nothing that switches an output on should be restored this way: a restart must never switch anything on by itself.
Dependencies
Section titled “Dependencies”A file may name what it needs in a header; devices with the same needs share an environment:
# /// script# requires-python = ">=3.11"# dependencies = ["pyserial"]# ///See Python environments and secrets.
Make it fit a profile
Section titled “Make it fit a profile”If your device is a pressure gauge, a stage, a generator, a pump or a polarimeter, say so: profiles = [PressureSensor]. The state must then have the shape of the profile (names, units, channels), and the dashboard offers the matching widgets with no further work. Your device may have more fields and actions than the profile asks for. If the state is missing a field of the profile or has the wrong type, the device keeps running and the log shows an error that says what to fix.
Try it and debug it
Section titled “Try it and debug it”-
Save the file. The Devices page shows file changed; Restart runs the new code.
-
Look at the log of the device (Devices page, or the Log of its card on the dashboard) for errors.
-
To stop at breakpoints, run the device in your own editor:
Terminal window laborchestra dev devices/power_meter.pyIn VS Code, you need no command: LabOrchestra writes a debug configuration for every Python device into
.vscode/launch.jsonof the workspace by itself, and keeps it current when you add or change devices (an existinglaunch.jsonwith comments is left alone). Choose LabOrchestra: debug power_meter in the Run view. LabOrchestra also setspython.defaultInterpreterPathin.vscode/settings.jsonto a Python that has thelaborchestrapackage, so that the editor findsimport laborchestra. A path you have set yourself is never replaced, and neither is asettings.jsonwith comments.laborchestra devruns the device in your process, attached to the running server. The server’s own copy of it stops meanwhile (a serial port cannot be opened twice), and the dashboard marks the device as in editor. When your process ends, the server starts its own copy again. It works on the lab PC itself.
Share it
Section titled “Share it”A single file is a complete device. To share a driver between labs, put it into a Python package with an entry point: Device packages. If a device must handle very high data rates, as an oscilloscope does, write it in C# as a plugin.
Something wrong or missing on this page? Open a GitHub issue or use the form (no account needed).