diff --git a/docs/resources/index.md b/docs/resources/index.md
index 86aa4006dbc..d101fca9d08 100644
--- a/docs/resources/index.md
+++ b/docs/resources/index.md
@@ -175,6 +175,7 @@ library/agenbio
library/agilent
library/alpaqua
library/azenta
+library/beckman_coulter
library/bioer
library/biorad
library/boekel
diff --git a/docs/resources/library/beckman_coulter.md b/docs/resources/library/beckman_coulter.md
new file mode 100644
index 00000000000..af2e392ebd7
--- /dev/null
+++ b/docs/resources/library/beckman_coulter.md
@@ -0,0 +1,45 @@
+# Beckman Coulter
+
+Company page: [Beckman Coulter Life Sciences](https://www.beckman.com)
+
+Transcribed from the tip and labware classes of Biomek 5, Beckman Coulter's software for its Biomek
+liquid handlers. The labware is defined as Biomek defines it, under Biomek's class names (in
+quotes), whoever makes it. Tips are `BiomekTip`s, which also carry the tip's cone; wells are
+`BiomekWell`s, which also carry Biomek's outline of the well by height.
+
+## Tips
+
+| Description | Image | PLR definition |
+|-|-|-|
+| 'T50F'
Biomek tip, 50 uL, filter | | `beckman_coulter_biomek_tip_50uL_filter` |
+| 'T190F'
Biomek tip, 190 uL, filter | | `beckman_coulter_biomek_tip_190uL_filter` |
+| 'T230'
Biomek tip, 230 uL, no filter | | `beckman_coulter_biomek_tip_230uL` |
+| 'T1025F'
Biomek tip, 1025 uL, filter | | `beckman_coulter_biomek_tip_1025uL_filter` |
+| 'T1070'
Biomek tip, 1070 uL, no filter | | `beckman_coulter_biomek_tip_1070uL` |
+
+## Tip racks
+
+| Description | Image | PLR definition |
+|-|-|-|
+| 'BC50F'
Part no.: B85888
Biomek tip box: 96 T50F tips | | `beckman_coulter_biomek_96_tiprack_50uL_filter` |
+| 'BC190F'
Part no.: B85911
Biomek tip box: 96 T190F tips | | `beckman_coulter_biomek_96_tiprack_190uL_filter` |
+| 'BC230'
Part no.: B85906 (sterile), B85903 (non-sterile)
Biomek tip box: 96 T230 tips | | `beckman_coulter_biomek_96_tiprack_230uL` |
+| 'BC1025F'
Part no.: B85955
Biomek tip box: 96 T1025F tips | | `beckman_coulter_biomek_96_tiprack_1025uL_filter` |
+| 'BC1070'
Part no.: B85945 (sterile), B85940 (non-sterile)
Biomek tip box: 96 T1070 tips | | `beckman_coulter_biomek_96_tiprack_1070uL` |
+
+## Plates
+
+| Description | Image | PLR definition |
+|-|-|-|
+| 'Thermo96VB_PP'
96 round, V-bottomed wells; with its 'TiterplateLid' | | `beckman_coulter_biomek_96_wellplate_vb` |
+| 'BCFlat96'
Part no.: 609844
96 round, flat-bottomed wells; with its 'TiterplateLid' | | `beckman_coulter_biomek_96_wellplate_flat` |
+| 'BCDeep96Square'
Part no.: 140504
96 deep, square, V-bottomed wells | | `beckman_coulter_biomek_96_deepwell_square` |
+| 'Thomson_24w_Square_RB'
Part no.: 931568
24 square, round-bottomed wells; with its lid | | `beckman_coulter_biomek_24_wellplate_square_rb` |
+
+## Reservoirs
+
+| Description | Image | PLR definition |
+|-|-|-|
+| 'ThermoNUNC_350CB'
one flat-bottomed section; with its 'TiterplateLid' | | `beckman_coulter_biomek_reservoir_350cb` |
+| 'Reservoir'
Part no.: 148033
one flat-bottomed section | | `beckman_coulter_biomek_reservoir` |
+| 'ModularReservoir'
Part no.: 372795 (frame)
four V-bottomed sections | | `beckman_coulter_biomek_modular_reservoir` |
diff --git a/pylabrobot/beckman_coulter/__init__.py b/pylabrobot/beckman_coulter/__init__.py
new file mode 100644
index 00000000000..e113ad03137
--- /dev/null
+++ b/pylabrobot/beckman_coulter/__init__.py
@@ -0,0 +1 @@
+"""Beckman Coulter devices."""
diff --git a/pylabrobot/beckman_coulter/biomek_i7/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/__init__.py
new file mode 100644
index 00000000000..421a55e4014
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/__init__.py
@@ -0,0 +1 @@
+"""Beckman Coulter Biomek i7, driven over USB through its ACE boards."""
diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/__init__.py
new file mode 100644
index 00000000000..77a9b218380
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/__init__.py
@@ -0,0 +1,5 @@
+"""Reading an instrument's Biomek files into its declared configuration
+(`DeviceConfiguration.from_biomek`): Biomek's instrument file (`instrument_file.py`, over the
+variant-tree reader `variant_tree.py`) and the Master Controller's instrument record
+(`master_controller.py`), put together and checked against each other by `importer.py`. Read-only
+on every Biomek file, and standard library only."""
diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py
new file mode 100644
index 00000000000..37eb214676d
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py
@@ -0,0 +1,237 @@
+"""Biomek files built for tests: a variant-tree writer, and an instrument file (`.bif`) and a
+Master Controller instrument record written from a declared configuration, so the readers can be
+checked against inputs made in the test. Not a test module itself, and not used by the driver."""
+
+import struct
+import zlib
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.instrument_file import (
+ GEOMETRY,
+ LIST_SETTINGS,
+ NESTED_SETTINGS,
+ OPTIONAL_GEOMETRY,
+)
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.variant_tree import (
+ DICTIONARY,
+ HEADER_SIZE,
+ LIST,
+ Ref,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration
+
+
+class Array:
+ """An array variant: its vartype and its elements, as `variant_tree` reads them."""
+
+ def __init__(self, vartype: int, values: List[Any], fmt: Optional[str] = None):
+ self.vartype, self.values, self.fmt = vartype, values, fmt
+
+
+class Writer:
+ """Writes Python values as a variant stream: dicts as dictionaries, lists as lists, `Ref` as a
+ reference, `Array` as an array; None, bools, ints (int32), floats (double) and strings."""
+
+ def __init__(self) -> None:
+ self.objects = 0
+
+ @staticmethod
+ def string(text: str) -> bytes:
+ return struct.pack(" bytes:
+ if value is None:
+ return b"\x01"
+ if value is True:
+ return b"\x02"
+ if value is False:
+ return b"\x03"
+ if isinstance(value, int):
+ return b"\x06" + struct.pack(" bytes:
+ """An object definition's start: its index (the objects so far) and class id."""
+ head = b"\x0e" + struct.pack(" bytes:
+ """A decompressed variant-tree stream: its size, then `root`."""
+ body = Writer().variant(root)
+ return struct.pack(" bytes:
+ """A variant-tree file's bytes: the header, then the stream compressed."""
+ return b"\x00" * HEADER_SIZE + zlib.compress(data)
+
+
+# -- an instrument file ----------------------------------------------------------------------------
+
+PODS = {"left": "Pod1", "right": "Pod2"}
+POD_TYPES = {"multichannel": "MC", "span8": "SPAN8"}
+
+# Runtime state an instrument file carries in a pod entry beside its configuration, which the
+# reader leaves out.
+STATE = {"XPosition": 12.5, "Tip1": "none", "Z3Position": 4.0, "RT_Speed": 3, "LastTips": "T230"}
+
+
+def _pod_entry(side: str, pod: Dict[str, Any]) -> Dict[str, Any]:
+ settings = dict(pod["settings"])
+ entry: Dict[str, Any] = {
+ "Name": PODS[side],
+ "PodName": pod["component"],
+ "PodType": POD_TYPES[pod["module_type"]],
+ "LeftPod": side == "left",
+ "CmdGen": {
+ "Conversion": {
+ f"{axis}{part}": c[key]
+ for axis, c in pod["conversion"].items()
+ for part, key in (("Const", "const"), ("Offset", "offset"))
+ }
+ },
+ "Min": {axis: low for axis, (low, _) in pod["limits"].items()},
+ "Max": {axis: high for axis, (_, high) in pod["limits"].items()},
+ "ParkLocation": pod["park"],
+ "GripperModel": pod["gripper_model"],
+ "Obstacles": [
+ {
+ "Name": o["name"],
+ "Buffer": o["buffer"],
+ **{k.upper(): o[k] for k in ("x1", "x2", "y1", "y2", "z1", "z2") if k in o},
+ }
+ for o in pod["obstacles"]
+ ],
+ }
+ for name, key in GEOMETRY.items():
+ entry[key] = pod["geometry"][name]
+ for name, key in OPTIONAL_GEOMETRY.items():
+ if name in pod["geometry"]:
+ entry[key] = pod["geometry"][name]
+ if "GripperSqueezeForce" in settings:
+ entry["Gripper"] = {"SqueezeForce": settings.pop("GripperSqueezeForce")}
+ for path in NESTED_SETTINGS:
+ value = settings.pop("/".join(path), None)
+ if value is not None:
+ node = entry
+ for key in path[:-1]:
+ node = node.setdefault(key, {})
+ node[path[-1]] = value
+ for key, value in settings.items():
+ entry[key] = list(value) if key in LIST_SETTINGS else value
+ entry.update(STATE)
+ return entry
+
+
+def instrument_file_tree(configuration: DeviceConfiguration, deck: str = "Deck1") -> Dict[str, Any]:
+ """What an instrument file holds for `configuration`, as plain values for `Writer`: the two pod
+ entries (with runtime state beside them) and the default deck, with another deck that is not the
+ default."""
+ data = configuration.to_dict()
+ pipettor: Dict[str, Any] = {"SerialNumber": data["instrument_serial_number"]}
+ for side, pod in data["pods"].items():
+ pipettor[PODS[side]] = _pod_entry(side, pod)
+ positions = {
+ name: {
+ **{f"{a}{n}": p["corners"][n][i] for n in p["corners"] for i, a in enumerate("XYZ")},
+ "XSpan": p["x_span"],
+ "YSpan": p["y_span"],
+ **{f"Framed{n}": how for n, how in p["framed"].items()},
+ }
+ for name, p in data["deck_positions"].items()
+ }
+ groups = {
+ a["name"]: {
+ "Type": a["alp_type"],
+ "column": a["column"],
+ "row": a["row"],
+ "Positions": {name: {} for name in a["positions"]},
+ **({"X1": a["x1"]} if a.get("x1") is not None else {}),
+ }
+ for a in data["deck_layout"]
+ }
+ return {
+ "Devices": {"Pipettor1": pipettor},
+ "Decks": {
+ "Other": {"IsDefault": False, "Positions": {}, "Groups": {}},
+ deck: {"IsDefault": True, "Positions": positions, "Groups": groups},
+ },
+ }
+
+
+def write_instrument_file(configuration: DeviceConfiguration, path: Union[str, Path]) -> None:
+ Path(path).write_bytes(container(stream(instrument_file_tree(configuration))))
+
+
+# -- a Master Controller instrument record -------------------------------------------------------
+
+PUMP_CONFIGURE = "<8I2iH" # the pump's Configure layout, which its record packs
+
+
+def _motor(axis: Dict[str, Any]) -> str:
+ limits = axis["limits"]
+ configure = bytes.fromhex(axis["configure"])
+ vmin = amin = 0
+ if axis["device"] == 0x12:
+ (min_start, max_start, vmin, _vmax, min_cutoff, max_cutoff, amin, _amax, _pmin, _pmax,
+ backlash) = struct.unpack(PUMP_CONFIGURE, configure) # fmt: skip
+ config = f"#( {min_start} {max_start} {min_cutoff} {max_cutoff} {backlash})"
+ jmax = "#f"
+ else:
+ config = "#vu8(" + " ".join(str(b) for b in configure) + ")"
+ jmax = str(limits["max_jerk"])
+ fields = [
+ "", axis["name"], axis["device"], axis["index"], 0, limits["min_position"],
+ limits["max_position"], axis["home_position"], axis["hysteresis"], vmin,
+ limits["max_velocity"], amin, limits["max_acceleration"], 0, jmax, "#f", config,
+ ] # fmt: skip
+ return "#(" + " ".join(str(f) for f in fields) + ")"
+
+
+def record_text(configuration: DeviceConfiguration) -> str:
+ """The Master Controller's instrument record for `configuration`, as its database holds it."""
+ arms: List[str] = []
+ for side, pod in configuration.pods.items():
+ kind = {"multichannel": "mc", "span8": "span8"}[pod.module_type]
+ motors = " ".join(_motor(a) for a in configuration.modules[pod.module_type])
+ arms.append(f'#( "{pod.module_serial_number}" {side} {kind} #({motors}))')
+ return f'#( "{configuration.chassis_serial_number}" ' + " ".join(arms) + ")"
+
+
+def write_record(configuration: DeviceConfiguration, path: Union[str, Path]) -> None:
+ Path(path).write_text(record_text(configuration) + "\n", encoding="utf-8")
+
+
+def write_database(texts: List[Tuple[str, str]], path: Union[str, Path]) -> None:
+ """A Master Controller database holding only its `instrument` table: (name, record) rows."""
+ import sqlite3
+
+ db = sqlite3.connect(str(path))
+ try:
+ with db:
+ db.execute("CREATE TABLE instrument (name TEXT, definition TEXT)")
+ db.executemany("INSERT INTO instrument VALUES (?, ?)", texts)
+ finally:
+ db.close()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer.py
new file mode 100644
index 00000000000..acc5c65a03b
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer.py
@@ -0,0 +1,174 @@
+"""Make an instrument's declared configuration from its Biomek files, and check it against them.
+
+`import_configuration` is the one way a declared configuration is made
+(`DeviceConfiguration.from_biomek`):
+1. the instrument file gives the pods, the deck's positions and its layout
+ (`instrument_file.read_instrument_file`);
+2. the Master Controller's instrument record gives the motor tables and the modules' serial
+ numbers (`master_controller.read_master_controller`);
+3. the two must describe one instrument: an arm on the same sides in both, each pod's arm type in
+ the record, and every travel window the instrument file gives inside the motor's own limits;
+4. `sources` records each source's path, kind, read time and the fingerprint of the values taken
+ from it.
+
+`check_sources` reads the recorded sources again and lists what changed since.
+"""
+
+import datetime
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.instrument_file import read_instrument_file
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.master_controller import (
+ read_master_controller,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import (
+ SOURCES,
+ DeviceConfiguration,
+ SourcesCheck,
+ differences,
+ fingerprint,
+ source_parts,
+)
+
+
+def _inconsistencies(
+ instrument_file: Dict[str, Any], master_controller: Dict[str, Any]
+) -> List[str]:
+ """How the two sources disagree about the instrument, one sentence each."""
+ problems = []
+ serials = master_controller["module_serial_numbers"]
+ for side in sorted(set(instrument_file["pods"]) | set(serials)):
+ pod = instrument_file["pods"].get(side)
+ if pod is None or side not in serials:
+ problems.append(
+ f"the {side} arm is in the {'Master Controller record' if pod is None else 'instrument file'}"
+ " only"
+ )
+ continue
+ if pod["module_type"] not in master_controller["modules"]:
+ problems.append(f"the {side} pod is a {pod['module_type']}; the record has no such arm")
+ continue
+ axes = {a["name"]: a for a in master_controller["modules"][pod["module_type"]]}
+ for axis, (low, high) in pod["limits"].items():
+ conversion = pod["conversion"].get(axis)
+ if conversion is None or axis not in axes:
+ continue
+ ends = sorted(round((v + conversion["offset"]) * conversion["const"]) for v in (low, high))
+ limits = axes[axis]["limits"]
+ if ends[0] < limits["min_position"] or ends[1] > limits["max_position"]:
+ problems.append(
+ f"the {side} pod's {axis} travel, counts {ends}, is outside the motor's "
+ f"[{limits['min_position']}, {limits['max_position']}]"
+ )
+ return problems
+
+
+def _now() -> str:
+ return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
+
+
+def import_configuration(
+ bif: Union[str, Path],
+ master_controller_db: Optional[Union[str, Path]] = None,
+ master_controller_record: Optional[Union[str, Path]] = None,
+ chassis_serial_number: Optional[str] = None,
+) -> DeviceConfiguration:
+ """`DeviceConfiguration.from_biomek`.
+
+ Raises:
+ ValueError: for files that do not describe one consistent instrument.
+ """
+ instrument_file = read_instrument_file(bif)
+ master_controller = read_master_controller(
+ master_controller_db=master_controller_db,
+ master_controller_record=master_controller_record,
+ chassis_serial_number=chassis_serial_number,
+ )
+ problems = _inconsistencies(instrument_file, master_controller)
+ if problems:
+ raise ValueError(
+ "the instrument file and the Master Controller's record do not describe one instrument: "
+ + "; ".join(problems)
+ )
+ pods = {
+ side: {**pod, "module_serial_number": master_controller["module_serial_numbers"][side]}
+ for side, pod in instrument_file["pods"].items()
+ }
+ config = DeviceConfiguration.from_dict({
+ "generic": False,
+ "chassis_serial_number": master_controller["chassis_serial_number"],
+ "instrument_serial_number": instrument_file["instrument_serial_number"],
+ "pods": pods,
+ "deck_positions": instrument_file["deck_positions"],
+ "deck_layout": instrument_file["deck_layout"],
+ "modules": master_controller["modules"],
+ }) # fmt: skip
+ fingerprints = config.fingerprints()
+ read_at = _now()
+ config.sources = {
+ "instrument_file": {
+ "kind": "bif",
+ "path": str(Path(bif).resolve()),
+ "read_at": read_at,
+ "fingerprint": fingerprints["instrument_file"],
+ },
+ "master_controller": {
+ "kind": "database" if master_controller_db is not None else "record",
+ "path": str(Path(master_controller_db or master_controller_record).resolve()), # type: ignore[arg-type]
+ "read_at": read_at,
+ "fingerprint": fingerprints["master_controller"],
+ },
+ }
+ return config
+
+
+def _read_again(config: DeviceConfiguration, name: str, path: Path) -> Dict[str, Any]:
+ """The serialized configuration with the values from source `name` read again from `path`."""
+ data = config.to_dict()
+ if name == "instrument_file":
+ fresh = read_instrument_file(path)
+ data["instrument_serial_number"] = fresh["instrument_serial_number"]
+ data["deck_positions"] = fresh["deck_positions"]
+ data["deck_layout"] = fresh["deck_layout"]
+ data["pods"] = {
+ side: {**pod, "module_serial_number": data["pods"].get(side, {}).get("module_serial_number")}
+ for side, pod in fresh["pods"].items()
+ }
+ else:
+ kind = config.sources[name].get("kind")
+ fresh = read_master_controller(
+ master_controller_db=path if kind == "database" else None,
+ master_controller_record=path if kind == "record" else None,
+ chassis_serial_number=config.chassis_serial_number,
+ )
+ data["chassis_serial_number"] = fresh["chassis_serial_number"]
+ data["modules"] = fresh["modules"]
+ for side, pod in data["pods"].items():
+ pod["module_serial_number"] = fresh["module_serial_numbers"].get(side)
+ # Through the dataclasses, so both sides are serialized the same way.
+ return DeviceConfiguration.from_dict(data).to_dict()
+
+
+def check_sources(config: DeviceConfiguration) -> SourcesCheck:
+ """`DeviceConfiguration.check_sources`.
+
+ Raises:
+ ValueError: for a source that is there but no longer reads as one (the reader's own error).
+ """
+ changed: List[str] = []
+ unavailable: List[str] = []
+ for name in SOURCES:
+ source = config.sources.get(name, {})
+ if "path" not in source:
+ unavailable.append(f"{name}: no path recorded")
+ continue
+ path = Path(source["path"])
+ if not path.exists():
+ unavailable.append(f"{name}: {path} not found")
+ continue
+ fresh = source_parts(_read_again(config, name, path))[name]
+ if fingerprint(fresh) != source["fingerprint"]:
+ declared = source_parts(config.to_dict())[name]
+ changed += [f"{name}: {line}" for line in differences(declared, fresh)]
+ return SourcesCheck(changed=changed, unavailable=unavailable)
diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer_tests.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer_tests.py
new file mode 100644
index 00000000000..bd69ce15b6d
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer_tests.py
@@ -0,0 +1,105 @@
+"""`DeviceConfiguration.from_biomek` end to end, on an instrument file and a Master Controller record
+written in the test, and `check_sources` finding what changed in them since."""
+
+import dataclasses
+import tempfile
+import unittest
+from pathlib import Path
+
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.files_tests_support import (
+ write_instrument_file,
+ write_record,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import (
+ DeviceConfiguration,
+ differences,
+)
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import (
+ as_instrument,
+ generic_configuration,
+)
+
+
+def instrument() -> DeviceConfiguration:
+ """The generic configuration as one instrument's: serial numbers, a measured hysteresis."""
+ config = as_instrument(generic_configuration())
+ config.instrument_serial_number = "TEST0000001"
+ for side, pod in config.pods.items():
+ pod.settings["HeadSerialNumber"] = f"HEAD-{side}"
+ next(a for a in config.modules["span8"] if a["name"] == "Z5")["hysteresis"] = 9
+ return config
+
+
+class ImportTests(unittest.TestCase):
+ def setUp(self) -> None:
+ folder = tempfile.TemporaryDirectory()
+ self.addCleanup(folder.cleanup)
+ self.bif = Path(folder.name) / "Biomek_i7.bif"
+ self.record = Path(folder.name) / "record.txt"
+ self.config = instrument()
+ write_instrument_file(self.config, self.bif)
+ write_record(self.config, self.record)
+
+ def imported(self) -> DeviceConfiguration:
+ return DeviceConfiguration.from_biomek(self.bif, master_controller_record=self.record)
+
+ def test_importing_gives_the_configuration_the_files_were_written_from(self) -> None:
+ imported = self.imported()
+ expected, got = self.config.to_dict(), imported.to_dict()
+ expected.pop("sources")
+ sources = got.pop("sources")
+ self.assertEqual(differences(expected, got), [])
+ self.assertEqual(sources["instrument_file"]["kind"], "bif")
+ self.assertEqual(sources["master_controller"]["kind"], "record")
+ self.assertEqual(Path(sources["instrument_file"]["path"]), self.bif.resolve())
+ self.assertEqual(imported.unrecorded_changes(), [])
+ path = self.bif.parent / "configuration.json"
+ imported.save(path)
+ self.assertEqual(DeviceConfiguration.load(path).to_dict(), imported.to_dict())
+
+ def test_a_travel_window_outside_its_motors_limits_is_refused(self) -> None:
+ config = instrument()
+ low, high = config.pods["left"].limits["X"]
+ config.pods["left"].limits["X"] = (low, high + 1000.0)
+ write_instrument_file(config, self.bif)
+ with self.assertRaisesRegex(ValueError, "left pod's X travel.*outside the motor's"):
+ self.imported()
+
+ def test_unchanged_sources_check_clean(self) -> None:
+ check = self.imported().check_sources()
+ self.assertEqual((check.changed, check.unavailable), ([], []))
+
+ def test_a_re_measured_hysteresis_is_found(self) -> None:
+ imported = self.imported()
+ remeasured = instrument()
+ next(a for a in remeasured.modules["span8"] if a["name"] == "Z5")["hysteresis"] = 10
+ write_record(remeasured, self.record)
+ changed = imported.check_sources().changed
+ self.assertEqual(len(changed), 1)
+ self.assertRegex(changed[0], r"^master_controller: modules/span8\[\d+\]/hysteresis: 9 -> 10$")
+
+ def test_a_re_framed_position_is_found(self) -> None:
+ imported = self.imported()
+ reframed = instrument()
+ position = reframed.deck_positions["P6"]
+ corners = dict(position.corners)
+ corners[1] = (corners[1][0] + 0.05, corners[1][1], corners[1][2])
+ reframed.deck_positions["P6"] = dataclasses.replace(position, corners=corners)
+ write_instrument_file(reframed, self.bif)
+ changed = imported.check_sources().changed
+ self.assertEqual(len(changed), 1)
+ self.assertTrue(changed[0].startswith("instrument_file: deck_positions/P6/corners/1[0]"))
+
+ def test_sources_not_found_are_unavailable(self) -> None:
+ imported = self.imported()
+ self.record.unlink()
+ check = imported.check_sources()
+ self.assertEqual(check.changed, [])
+ self.assertEqual(len(check.unavailable), 1)
+ self.assertIn("master_controller", check.unavailable[0])
+ check = generic_configuration().check_sources() # fingerprints only: no paths
+ self.assertEqual(len(check.unavailable), 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py
new file mode 100644
index 00000000000..dc11ff06384
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py
@@ -0,0 +1,222 @@
+"""What a declared configuration takes from Biomek's instrument file (`.bif`).
+
+From the live pod entries `Devices/Pipettor1/Pod1` and `Pod2`, per pod:
+- the counts conversions, travel limits and park location;
+- the geometry (the collision model's dimensions);
+- every other scalar setting, and the few kept as a dictionary (`NESTED_SETTINGS`);
+- the gripper model;
+- the deck obstacles Biomek keeps per pod (boxes, an absent bound open);
+
+and from the default deck, its positions with a corner per pod, and its ALPs.
+
+The per-device entries are used, not the pod-type defaults under `HardwareSetupInfo/PodTypes`:
+they are what reproduces Biomek's logged travel (see `PodGeometry`). Runtime state the file also
+carries (positions, tips, gripped labware, `RT_*`) is left out: Biomek rewrites it during ordinary
+runs, and it is not configuration.
+"""
+
+from pathlib import Path
+from typing import Any, Dict, List, Tuple, Union
+
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.variant_tree import Tree, parse_file, plain
+
+MODULE_TYPES = {"MC": "multichannel", "SPAN8": "span8"}
+
+# Geometry fields (driver `PodGeometry`) and the pod entry's keys they come from.
+GEOMETRY = {
+ "bridge_x_span": "BridgeXSpan",
+ "bridge_to_head_x_offset": "BridgeToHeadXOffset",
+ "mandrel1_x_offset": "Mandrel1XOffset",
+ "mandrel1_y_offset": "Mandrel1YOffset",
+ "mandrel_x_spacing": "MandrelXSpacing",
+ "mandrel_y_spacing": "MandrelYSpacing",
+ "avoidance_margin": "AvoidanceMargin",
+ "pod_x_span": "PodXSpan",
+ "pod_y_span": "PodYSpan",
+ "gripper_x_offset": "GripperXOffset",
+ "gripper_y_offset": "GripperYOffset",
+ "gripper_z_offset": "GripperZOffset",
+ "frame_safety_left": "Frame_Safety_L",
+ "frame_safety_right": "Frame_Safety_R",
+ "additional_safe_height": "AdditionalSafeHeight",
+ "additional_safe_height_gripper": "AdditionalSafeHeightGripper",
+}
+OPTIONAL_GEOMETRY = {
+ "mandrels_x": "MandrelsX",
+ "mandrels_y": "MandrelsY",
+ "sub_mandrel_safe_height": "SubMandrelSafeHeight",
+}
+
+# Runtime state Biomek writes back into the file: where things are and what is held.
+STATE_KEYS = {
+ "CurrentSpeed", "DPosition", "GGPosition", "GRPosition", "GYPosition", "GZPosition",
+ "GripSide", "GrippedLabware", "GrippedLabwareOffsets", "HasGripperProbes", "LastOperation",
+ "LastTips", "LastValidation", "PositionSaved", "SPosition", "Squeeze", "SqueezeForce", "Tips",
+ "TipsFrom", "TipsFromLW", "TipsSelected", "XPosition", "YPosition", "ZPosition",
+} # fmt: skip
+
+# Per-probe lists of numbers, kept as settings like the scalars (the seat per probe).
+LIST_SETTINGS = {"LoadingOffsets", "BrokenTips"}
+
+# Settings Biomek keeps as a dictionary in the pod entry, taken as that dictionary under the key's
+# path: a Multichannel's mandrel A1 from the pod (`Head/PodToMandrel1`: X, Y, Z in cm, Z the bare
+# mandrels' end), a Span-8 probe's tip hub (`DefaultTipHubInfo`: Length, MinRadius, MaxRadius), a
+# Span-8's tubing bundle (`LLSWireModel`: where it leaves the probes, its anchor, its lowest point).
+NESTED_SETTINGS = (("Head", "PodToMandrel1"), ("DefaultTipHubInfo",), ("LLSWireModel",))
+
+
+def is_state(key: str) -> bool:
+ """Whether a pod entry's key is runtime state rather than configuration."""
+ if key.startswith("RT_") or key in STATE_KEYS:
+ return True
+ # Per channel or pump: Tip1..Tip8, Z1Position.., D1Position..
+ return (key.startswith("Tip") and key[3:].isdigit()) or (
+ key.endswith("Position") and key[0] in "ZD" and key[1:-8].isdigit()
+ )
+
+
+def _plain_dict(tree: Tree, obj: Any) -> Dict[str, Any]:
+ """A dictionary as plain JSON values, without the reader's bookkeeping keys."""
+
+ def clean(v: Any) -> Any:
+ if isinstance(v, dict):
+ return {k: clean(x) for k, x in v.items() if not k.startswith("$")}
+ if isinstance(v, list):
+ return [clean(x) for x in v]
+ return v
+
+ return clean(plain(obj, tree.objects, inline=False)) # type: ignore[no-any-return]
+
+
+def _unit_of(axis: str) -> str:
+ if axis == "GR":
+ return "deg"
+ if axis[0] == "D":
+ return "uL"
+ return "cm"
+
+
+def _pod(tree: Tree, pod: Any) -> Tuple[str, Dict[str, Any]]:
+ get = tree.deref
+ e = {k: get(v) for k, v in pod.entries.items()}
+ conversion_entries = get(get(e["CmdGen"]).entries["Conversion"]).entries
+ conversion = {}
+ for key, value in conversion_entries.items():
+ if key.endswith("Const"):
+ axis = key[: -len("Const")]
+ conversion[axis] = {
+ "const": value,
+ "offset": conversion_entries[f"{axis}Offset"],
+ "unit": _unit_of(axis),
+ }
+ low, high = get(e["Min"]).entries, get(e["Max"]).entries
+ limits = {k: [low[k], high[k]] for k in high if k in low}
+ geometry: Dict[str, Any] = {name: e[key] for name, key in GEOMETRY.items()}
+ geometry.update({name: e[key] for name, key in OPTIONAL_GEOMETRY.items() if key in e})
+ used = set(GEOMETRY.values()) | set(OPTIONAL_GEOMETRY.values())
+ settings: Dict[str, Any] = {
+ k: v
+ for k, v in e.items()
+ if k not in used and not is_state(k) and isinstance(v, (bool, int, float, str))
+ }
+ for k, v in e.items():
+ items = getattr(v, "items", None)
+ if k not in used and not is_state(k) and k in LIST_SETTINGS and isinstance(items, list):
+ settings[k] = [get(x) for x in items]
+ for path in NESTED_SETTINGS:
+ node: Any = pod
+ for key in path:
+ entries = getattr(get(node), "entries", None)
+ node = entries.get(key) if entries is not None else None
+ if node is None:
+ break
+ if node is not None:
+ settings["/".join(path)] = _plain_dict(tree, get(node))
+ # The force a grip closes with (`SF` on GG; Biomek sends it as is). The pod's own
+ # `SqueezeForce` is runtime state; the gripper's is the setting.
+ gripper = get(e["Gripper"]).entries if "Gripper" in e else {}
+ if "SqueezeForce" in gripper:
+ settings["GripperSqueezeForce"] = gripper["SqueezeForce"]
+ side = "left" if e["LeftPod"] else "right"
+ return side, {
+ "component": e["PodName"],
+ "module_type": MODULE_TYPES[e["PodType"]],
+ "source": f"bif:Devices/Pipettor1/{e['Name']}",
+ "conversion": conversion,
+ "limits": limits,
+ "geometry": geometry,
+ "park": _plain_dict(tree, e["ParkLocation"]),
+ "settings": settings,
+ "gripper_model": _plain_dict(tree, e["GripperModel"]),
+ "obstacles": [
+ {
+ "name": o["Name"],
+ "buffer": o.get("Buffer", 0.0),
+ **{k.lower(): o[k] for k in ("X1", "X2", "Y1", "Y2", "Z1", "Z2") if k in o},
+ }
+ for o in (_plain_dict(tree, get(item)) for item in get(e["Obstacles"]).items)
+ ],
+ }
+
+
+def _default_deck(tree: Tree) -> Tuple[str, Any]:
+ get = tree.deref
+ decks = get(tree.root.entries["Decks"])
+ name = next(k for k in decks.entries if get(decks.entries[k]).entries.get("IsDefault"))
+ return name, get(decks.entries[name])
+
+
+def _positions(tree: Tree) -> Dict[str, Dict[str, Any]]:
+ """The default deck's positions: each one's corner per pod (`X`/`Y`/`Z`), its spans and
+ how each corner was framed."""
+ get = tree.deref
+ positions = {}
+ for name, ref in get(_default_deck(tree)[1].entries["Positions"]).entries.items():
+ e = get(ref).entries
+ if not all(f"{a}{n}" in e for a in "XYZ" for n in (1, 2)):
+ continue
+ positions[name] = {
+ "corners": {str(n): [e[f"X{n}"], e[f"Y{n}"], e[f"Z{n}"]] for n in (1, 2)},
+ "x_span": e["XSpan"],
+ "y_span": e["YSpan"],
+ "framed": {str(n): e[f"Framed{n}"] for n in (1, 2) if f"Framed{n}" in e},
+ }
+ return dict(sorted(positions.items()))
+
+
+def _layout(tree: Tree) -> List[Dict[str, Any]]:
+ """The default deck's ALPs (`Decks//Groups`): each one's name, `Type`, pin `column` and
+ `row`, its positions' names and its left edge `X1` (cm), left to right."""
+ get = tree.deref
+ layout = []
+ for name, ref in get(_default_deck(tree)[1].entries["Groups"]).entries.items():
+ e = get(ref).entries
+ positions = get(e.get("Positions"))
+ layout.append({
+ "name": name,
+ "alp_type": e["Type"],
+ "column": e["column"],
+ "row": e["row"],
+ "positions": list(positions.entries) if positions is not None and positions.entries else [],
+ "x1": e.get("X1"),
+ }) # fmt: skip
+ return sorted(layout, key=lambda a: (a["column"], a["row"]))
+
+
+def read_instrument_file(path: Union[str, Path]) -> Dict[str, Any]:
+ """The part of a declared configuration an instrument file gives, as `DeviceConfiguration`
+ serializes it: `instrument_serial_number`, `pods` (without their module serial numbers, which
+ the Master Controller's record gives), `deck_positions` and `deck_layout`.
+
+ Raises:
+ ParseError: for a file this reader cannot account for completely.
+ """
+ tree = parse_file(str(path))
+ pipettor = tree.deref(tree.deref(tree.root.entries["Devices"]).entries["Pipettor1"])
+ pods = dict(_pod(tree, tree.deref(pipettor.entries[name])) for name in ("Pod1", "Pod2"))
+ return {
+ "instrument_serial_number": pipettor.entries.get("SerialNumber"),
+ "pods": pods,
+ "deck_positions": _positions(tree),
+ "deck_layout": _layout(tree),
+ }
diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file_tests.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file_tests.py
new file mode 100644
index 00000000000..1c739b202d2
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file_tests.py
@@ -0,0 +1,84 @@
+"""What a declared configuration takes from an instrument file, read from one written in the test
+from the package's generic configuration."""
+
+import tempfile
+import unittest
+from pathlib import Path
+
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.files_tests_support import (
+ STATE,
+ container,
+ instrument_file_tree,
+ stream,
+ write_instrument_file,
+)
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.instrument_file import (
+ is_state,
+ read_instrument_file,
+)
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.variant_tree import ParseError
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration
+
+
+def configuration(): # type: ignore[no-untyped-def]
+ config = generic_configuration()
+ config.instrument_serial_number = "TEST0000001"
+ for side, pod in config.pods.items():
+ pod.settings["HeadSerialNumber"] = f"HEAD-{side}"
+ return config
+
+
+class InstrumentFileTests(unittest.TestCase):
+ def setUp(self) -> None:
+ folder = tempfile.TemporaryDirectory()
+ self.addCleanup(folder.cleanup)
+ self.path = Path(folder.name) / "Biomek_i7.bif"
+ self.config = configuration()
+ write_instrument_file(self.config, self.path)
+ self.read = read_instrument_file(self.path)
+ self.expected = self.config.to_dict()
+
+ def test_the_pods_come_back_as_written(self) -> None:
+ for side, pod in self.expected["pods"].items():
+ with self.subTest(side=side):
+ # The module serial numbers are the Master Controller record's, not the instrument file's.
+ expected = {k: v for k, v in pod.items() if k != "module_serial_number"}
+ self.assertEqual(self.read["pods"][side], expected)
+ self.assertEqual(self.read["instrument_serial_number"], "TEST0000001")
+
+ def test_the_default_deck_comes_back_as_written(self) -> None:
+ self.assertEqual(self.read["deck_positions"], self.expected["deck_positions"])
+ self.assertEqual(self.read["deck_layout"], self.expected["deck_layout"])
+
+ def test_runtime_state_is_left_out(self) -> None:
+ for side in ("left", "right"):
+ for key in STATE:
+ self.assertNotIn(key, self.read["pods"][side]["settings"])
+ for key in ("RT_Anything", "Tip8", "D3Position", "Z1Position", "GrippedLabware"):
+ self.assertTrue(is_state(key), key)
+ for key in ("TipLoadForceLimitSlope", "Tips2Load", "ZMargin"):
+ self.assertFalse(is_state(key), key)
+
+ def test_settings_kept_as_dictionaries_and_lists(self) -> None:
+ for side, pod in self.expected["pods"].items():
+ for key, value in pod["settings"].items():
+ if isinstance(value, (dict, list)):
+ self.assertEqual(self.read["pods"][side]["settings"][key], value, (side, key))
+
+ def test_a_position_without_both_corners_is_left_out(self) -> None:
+ tree = instrument_file_tree(self.config)
+ positions = tree["Decks"]["Deck1"]["Positions"]
+ name = next(iter(positions))
+ del positions[name]["Z2"]
+ self.path.write_bytes(container(stream(tree)))
+ self.assertNotIn(name, read_instrument_file(self.path)["deck_positions"])
+
+ def test_a_file_this_reader_cannot_account_for_is_refused(self) -> None:
+ data = stream(instrument_file_tree(self.config))
+ self.path.write_bytes(container(data[:4] + data[4:] + b"\x01"))
+ with self.assertRaises(ParseError):
+ read_instrument_file(self.path)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller.py
new file mode 100644
index 00000000000..9c8bdc4184c
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller.py
@@ -0,0 +1,218 @@
+"""What a declared configuration takes from Biomek's Master Controller: its instrument record.
+
+The Master Controller keeps one record per instrument it drives, in the `instrument` table of its
+database (`C:\\ProgramData\\Beckman Coulter\\Biomek Master Controller\\Log.db3`; the same file
+holds its logs). The record is the instrument's motor configuration, keyed by serial numbers:
+
+ #( ""
+ #( "" left|right mc|span8
+ #(#( ...) ...))
+ ...)
+
+Each `` holds, in order: the axis's name, device byte, index and mask; its minimum and
+maximum position; its home position (where Home All leaves it); its hysteresis (what the Master
+Controller adds to its targets, measured per instrument: non-zero on the Span-8 Z channels); its
+minimum and maximum velocity, acceleration and jerk (`#f` for none); a simulated flag; and its
+Configure parameters as sent to its board (`#vu8(...)`), or for a syringe pump a ``
+of its start and cutoff velocity limits and backlash, from which the pump's Configure parameters
+are packed. Every value checks against the Configure bytes the Master Controller sends at a cold
+start (the same limits; the same bytes). The record is rewritten only when the instrument's
+motors are changed or measured, and carries no runtime state.
+
+The record is read in one of two ways, to the same result:
+- from the database, read-only (`master_controller_db`), choosing the instrument by its chassis
+ serial number when the database holds more than one;
+- from a text file holding the record (`master_controller_record`), for a computer without the
+ database, or a Python without `sqlite3`.
+"""
+
+import re
+import struct
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+MODULE_TYPES = {"mc": "multichannel", "span8": "span8"}
+PUMP_DEVICE = 0x12
+
+_TOKEN = re.compile(r'\s*(#vu8\(|#\(|\(|\)|"(?:[^"\\]|\\.)*"|[^\s()"]+)')
+
+
+class Symbol(str):
+ """A bare word of the record (a name, `left`, `#f`), as opposed to a string."""
+
+
+def parse_record(text: str) -> List[Any]:
+ """Every top-level value of a record's text: vectors and lists as Python lists, byte vectors as
+ `bytes`, integers as `int`, `#t` / `#f` as `True` / `False`, strings as `str`, other words as
+ `Symbol`.
+
+ Raises:
+ ValueError: for text that is not a record.
+ """
+ tokens = []
+ at = 0
+ while text[at:].strip():
+ m = _TOKEN.match(text, at)
+ if m is None:
+ raise ValueError(f"the Master Controller record holds text this reader does not know at {at}")
+ tokens.append(m.group(1))
+ at = m.end()
+ pos = 0
+
+ def value() -> Any:
+ nonlocal pos
+ token = tokens[pos]
+ pos += 1
+ if token in ("#(", "("):
+ items = []
+ while tokens[pos] != ")":
+ items.append(value())
+ pos += 1
+ return items
+ if token == "#vu8(":
+ data = []
+ while tokens[pos] != ")":
+ data.append(int(tokens[pos]))
+ pos += 1
+ pos += 1
+ return bytes(data)
+ if token == ")":
+ raise ValueError("unbalanced ')' in the Master Controller record")
+ if token.startswith('"'):
+ return token[1:-1]
+ if token in ("#t", "#f"):
+ return token == "#t"
+ if re.fullmatch(r"-?\d+", token):
+ return int(token)
+ return Symbol(token)
+
+ out = []
+ try:
+ while pos < len(tokens):
+ out.append(value())
+ except IndexError as e:
+ raise ValueError("the Master Controller record ends inside a value") from e
+ return out
+
+
+def _axis(motor: List[Any]) -> Dict[str, Any]:
+ """One `` record as a declared configuration's axis."""
+ (_, name, device, index, _mask, pmin, pmax, phome, hysteresis, vmin, vmax, amin, amax, _jmin,
+ jmax, _simulated, config) = motor # fmt: skip
+ limits: Dict[str, int] = {"max_velocity": vmax, "max_acceleration": amax}
+ if device == PUMP_DEVICE:
+ _, min_start, max_start, min_cutoff, max_cutoff, backlash = config
+ configure = struct.pack(
+ "<8I2iH", min_start, max_start, vmin, vmax, min_cutoff, max_cutoff, amin, amax, pmin, pmax,
+ backlash,
+ ) # fmt: skip
+ else:
+ configure = config
+ limits["max_jerk"] = jmax if jmax is not False else 0
+ limits.update({"min_position": pmin, "max_position": pmax})
+ return {
+ "name": str(name),
+ "device": device,
+ "index": index,
+ "configure": configure.hex(),
+ "limits": limits,
+ "home_position": phome,
+ "hysteresis": hysteresis,
+ }
+
+
+def _instrument(record: List[Any]) -> Dict[str, Any]:
+ """One `` record as the part of a declared configuration it gives."""
+ if not record or record[0] != "":
+ raise ValueError("not a Master Controller instrument record")
+ modules: Dict[str, List[Dict[str, Any]]] = {}
+ module_serial_numbers: Dict[str, str] = {}
+ for arm in record[2:]:
+ if not arm or arm[0] != "":
+ raise ValueError("an instrument record entry that is not an arm")
+ _, serial, side, arm_type, motors = arm
+ if arm_type not in MODULE_TYPES:
+ raise ValueError(f"a {arm_type} arm, which this driver has no tables for")
+ module = MODULE_TYPES[arm_type]
+ if module in modules:
+ raise ValueError(f"two {module} arms in one instrument record")
+ modules[module] = [_axis(m) for m in motors]
+ module_serial_numbers[str(side)] = serial.upper()
+ return {
+ "chassis_serial_number": record[1].upper(),
+ "module_serial_numbers": module_serial_numbers,
+ "modules": modules,
+ }
+
+
+def _records(
+ master_controller_db: Optional[Union[str, Path]],
+ master_controller_record: Optional[Union[str, Path]],
+) -> List[str]:
+ if (master_controller_db is None) == (master_controller_record is None):
+ raise ValueError("give one of master_controller_db and master_controller_record")
+ if master_controller_record is not None:
+ return [Path(master_controller_record).read_text(encoding="utf-8")]
+ import contextlib
+ import sqlite3 # standard library; only needed for this way of reading the record
+
+ uri = Path(master_controller_db).resolve().as_uri() + "?mode=ro" # type: ignore[arg-type]
+ with contextlib.closing(sqlite3.connect(uri, uri=True)) as db: # closed, not only committed
+ return [row[0] for row in db.execute("SELECT definition FROM instrument ORDER BY name")]
+
+
+def read_master_controller(
+ master_controller_db: Optional[Union[str, Path]] = None,
+ master_controller_record: Optional[Union[str, Path]] = None,
+ chassis_serial_number: Optional[str] = None,
+) -> Dict[str, Any]:
+ """The part of a declared configuration the Master Controller's instrument record gives:
+ `chassis_serial_number`, `module_serial_numbers` (per side) and `modules` (the motor tables).
+
+ Args:
+ master_controller_db: its database (`Log.db3`), opened read-only.
+ master_controller_record: a text file holding the record, instead of the database.
+ chassis_serial_number: which instrument, when more than one record is found.
+
+ Raises:
+ ValueError: for neither or both sources, no record of that instrument, more than one record
+ and no chassis serial number to choose by, or a record this reader does not know.
+ """
+ found = [
+ _instrument(record)
+ for text in _records(master_controller_db, master_controller_record)
+ for record in parse_record(text)
+ ]
+ if chassis_serial_number is not None:
+ found = [r for r in found if r["chassis_serial_number"] == chassis_serial_number.upper()]
+ if len(found) != 1:
+ serials = [r["chassis_serial_number"] for r in found]
+ raise ValueError(
+ f"{len(found)} Master Controller instrument records"
+ + (f" for chassis {chassis_serial_number}" if chassis_serial_number else "")
+ + (f" ({', '.join(serials)}); pass chassis_serial_number" if len(found) > 1 else "")
+ )
+ return found[0]
+
+
+def write_record(text: str, path: Union[str, Path]) -> None:
+ """Write a record's text to a file `master_controller_record` reads, after checking it parses."""
+ for record in parse_record(text):
+ _instrument(record)
+ Path(path).write_text(text + "\n", encoding="utf-8")
+
+
+def record_text(
+ master_controller_db: Union[str, Path], chassis_serial_number: Optional[str] = None
+) -> str:
+ """The record's text as the database holds it, for `write_record`: the one instrument, or the one
+ with that chassis serial number."""
+ texts = _records(master_controller_db, None)
+ matches: List[Tuple[str, Dict[str, Any]]] = [
+ (t, _instrument(r)) for t in texts for r in parse_record(t)
+ ]
+ if chassis_serial_number is not None:
+ matches = [m for m in matches if m[1]["chassis_serial_number"] == chassis_serial_number.upper()]
+ if len(matches) != 1:
+ raise ValueError(f"{len(matches)} matching Master Controller instrument records")
+ return matches[0][0]
diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller_tests.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller_tests.py
new file mode 100644
index 00000000000..0432c192110
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller_tests.py
@@ -0,0 +1,115 @@
+"""What a declared configuration takes from the Master Controller's instrument record, read from a
+record written in the test from the package's generic configuration, as text and as a database."""
+
+import tempfile
+import unittest
+from pathlib import Path
+
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.files_tests_support import (
+ record_text,
+ write_database,
+ write_record,
+)
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.master_controller import (
+ Symbol,
+ parse_record,
+ read_master_controller,
+)
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.master_controller import (
+ write_record as save_record,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import (
+ as_instrument,
+ generic_configuration,
+)
+
+
+def instrument(chassis: str = "simulated00100000000000000000000") -> DeviceConfiguration:
+ """The generic configuration as an instrument's, with a measured hysteresis on a Span-8 Z."""
+ config = as_instrument(generic_configuration())
+ config.chassis_serial_number = chassis
+ z2 = next(a for a in config.modules["span8"] if a["name"] == "Z2")
+ z2["hysteresis"] = 11
+ return config
+
+
+class RecordTextTests(unittest.TestCase):
+ def test_values_of_each_kind(self) -> None:
+ parsed = parse_record('#( "ab\\"c" left 12 -3 #t #f (1 2) #vu8(0 255 7))')
+ self.assertEqual(
+ parsed, [["", 'ab\\"c', "left", 12, -3, True, False, [1, 2], b"\x00\xff\x07"]]
+ )
+ self.assertIsInstance(parsed[0][2], Symbol)
+ self.assertNotIsInstance(parsed[0][1], Symbol)
+
+ def test_text_that_is_not_a_record_is_refused(self) -> None:
+ for text in ("#(1 2", ")", '#(1 "unclosed)'):
+ with self.subTest(text=text), self.assertRaises(ValueError):
+ parse_record(text)
+
+
+class ReadTests(unittest.TestCase):
+ def setUp(self) -> None:
+ folder = tempfile.TemporaryDirectory()
+ self.addCleanup(folder.cleanup)
+ self.folder = Path(folder.name)
+ self.config = instrument()
+
+ def test_the_record_gives_the_motor_tables_and_serial_numbers(self) -> None:
+ path = self.folder / "record.txt"
+ write_record(self.config, path)
+ read = read_master_controller(master_controller_record=path)
+ self.assertEqual(
+ read["modules"], self.config.modules
+ ) # pumps' Configure packed from the record
+ self.assertEqual(
+ read["chassis_serial_number"], "SIMULATED00100000000000000000000"
+ ) # upper case
+ self.assertEqual(
+ read["module_serial_numbers"],
+ {side: pod.module_serial_number for side, pod in self.config.pods.items()},
+ )
+
+ def test_a_database_gives_the_same(self) -> None:
+ db = self.folder / "Log.db3"
+ write_database([("one", record_text(self.config))], db)
+ record = self.folder / "record.txt"
+ write_record(self.config, record)
+ self.assertEqual(
+ read_master_controller(master_controller_db=db),
+ read_master_controller(master_controller_record=record),
+ )
+
+ def test_an_instrument_is_chosen_by_its_chassis(self) -> None:
+ db = self.folder / "Log.db3"
+ other = instrument(chassis="B" * 32)
+ write_database([("a", record_text(self.config)), ("b", record_text(other))], db)
+ with self.assertRaisesRegex(ValueError, "2 Master Controller instrument records.*pass"):
+ read_master_controller(master_controller_db=db)
+ chosen = read_master_controller(master_controller_db=db, chassis_serial_number="b" * 32)
+ self.assertEqual(chosen["chassis_serial_number"], "B" * 32)
+ with self.assertRaisesRegex(ValueError, "0 Master Controller instrument records for chassis"):
+ read_master_controller(master_controller_db=db, chassis_serial_number="0" * 32)
+
+ def test_one_source_exactly(self) -> None:
+ path = self.folder / "record.txt"
+ write_record(self.config, path)
+ with self.assertRaisesRegex(ValueError, "one of"):
+ read_master_controller()
+ with self.assertRaisesRegex(ValueError, "one of"):
+ read_master_controller(master_controller_db=path, master_controller_record=path)
+
+ def test_records_this_reader_does_not_know_are_refused(self) -> None:
+ text = record_text(self.config)
+ for bad, message in (
+ ("#( 1)", "not a Master Controller instrument record"),
+ (text.replace(" span8 #(", " span96 #("), "span96 arm"),
+ (text.replace(" span8 #(", " mc #("), "two multichannel arms"),
+ ):
+ with self.subTest(message=message), self.assertRaisesRegex(ValueError, message):
+ save_record(bad, self.folder / "record.txt")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree.py
new file mode 100644
index 00000000000..6ea4b7d1b5f
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree.py
@@ -0,0 +1,415 @@
+"""Read Biomek's variant-tree files: the instrument file (`.bif`), and labware / tip class data.
+
+Container: 5 header bytes, then zlib. Inside is one int32 size and one variant. A variant starts
+with one code byte; its low nibble is the type and bit 0x10 marks an interface reference:
+
+ 0x00 empty 0x01 null 0x02 true 0x03 false 0x04 byte 0x05 int16 0x06 int32
+ 0x07 single 0x08 double 0x09 currency (int64 / 10000) 0x0A date (double, days)
+ 0x0B string (int32 length, UTF-16LE) 0x0C error (int32)
+ 0x0D reference to an object defined earlier (int32 index)
+ 0x0E object definition: int32 index (= objects so far), 16-byte class id, then the object's body
+ 0x0F array: vartype byte, uint16 dims, dims x (uint32 count, int32 lbound), then the elements
+
+Two classes carry most of a file:
+
+- a dictionary: a flag byte; if non-zero a class id follows, and with flag 1 an extension body of
+ that class comes first; then an int32 count of (string key, variant value) entries;
+- a list: an int32 count of variants.
+
+The other classes' bodies (`EXTENSIONS`, `OBJECTS`) were measured on the files in hand. `parse`
+refuses to finish with any byte unaccounted for, so a file in a format not seen here is refused,
+not misread.
+"""
+
+import struct
+import uuid
+import zlib
+from dataclasses import dataclass, field
+from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple
+
+HEADER_SIZE = 5
+
+
+def _class_id(text: str) -> bytes:
+ return uuid.UUID(text).bytes_le
+
+
+DICTIONARY = _class_id("E4C29FFF-BCE3-44DB-BEB6-5B5B6EBC0DF1")
+LIST = _class_id("62DBE1C1-B344-4AB4-804F-73722341CBE5")
+DATA_SET_MANAGER = _class_id("B6D3BEC0-0085-4F00-A09A-C310B1DAFB72")
+DATA_SET = _class_id("C025C3B2-323C-4AC8-B61D-1F13EFFFE37F")
+LABWARE = _class_id("739C5987-FD91-4D70-82CB-2A5B768E3CCB")
+WORKSPACE = _class_id("23008335-C70E-46F0-87A8-4948F25298E8")
+DECK_POSITION = _class_id("0E7CDB5A-E774-4F1A-A72E-A013F06ED62A")
+PROMISE = _class_id("FD7B3B46-B8DA-4E47-B7FF-51B975DE468D")
+WELL_VALUES = _class_id("51297284-DD58-4725-A9B9-429BD5610D69")
+
+CLASS_NAMES = {
+ DICTIONARY: "dictionary",
+ LIST: "list",
+ DATA_SET_MANAGER: "data set manager",
+ DATA_SET: "data set",
+ LABWARE: "labware",
+ WORKSPACE: "workspace",
+ DECK_POSITION: "deck position",
+ PROMISE: "promise",
+ WELL_VALUES: "well values",
+}
+
+# Array vartypes whose elements are fixed-size values, read as raw bytes.
+_ARRAY_RAW = {
+ 0x02: "h",
+ 0x03: "i",
+ 0x04: "f",
+ 0x05: "d",
+ 0x06: "q",
+ 0x07: "d",
+ 0x0A: "i",
+ 0x0B: "h",
+ 0x11: "B",
+}
+
+
+class ParseError(Exception):
+ """The file is not a variant tree as this reader knows it."""
+
+
+@dataclass
+class Obj:
+ """An object definition: its class, what its extension or own body read, and its entries."""
+
+ index: int
+ class_id: bytes
+ flag: Optional[int] = None
+ extension_class_id: Optional[bytes] = None
+ extension: Any = None
+ entries: Optional[Dict[str, Any]] = None
+ items: Optional[List[Any]] = None
+
+ @property
+ def class_name(self) -> str:
+ return CLASS_NAMES.get(self.class_id, str(uuid.UUID(bytes_le=self.class_id)))
+
+ @property
+ def extension_name(self) -> Optional[str]:
+ if self.extension_class_id is None:
+ return None
+ return CLASS_NAMES.get(
+ self.extension_class_id, str(uuid.UUID(bytes_le=self.extension_class_id))
+ )
+
+
+@dataclass
+class Ref:
+ """A reference to an object defined earlier in the stream."""
+
+ index: int
+
+
+@dataclass
+class Currency:
+ value: int # x 10000
+
+
+@dataclass
+class Date:
+ days: float # since 1899-12-30
+
+
+@dataclass
+class Tree:
+ root: Any
+ objects: List[Obj] = field(default_factory=list)
+
+ def deref(self, value: Any) -> Any:
+ """`value`, or the object it refers to."""
+ return self.objects[value.index] if isinstance(value, Ref) else value
+
+
+class Reader:
+ def __init__(self, data: bytes):
+ self.data = data
+ self.pos = 0
+ self.objects: List[Obj] = []
+
+ # -- primitives --------------------------------------------------------------------------------
+
+ def take(self, n: int) -> bytes:
+ if n < 0 or self.pos + n > len(self.data):
+ raise ParseError(f"read of {n} bytes past the end at {self.pos}")
+ chunk = self.data[self.pos : self.pos + n]
+ self.pos += n
+ return chunk
+
+ def unpack(self, fmt: str) -> Any:
+ return struct.unpack("<" + fmt, self.take(struct.calcsize("<" + fmt)))[0]
+
+ def string(self) -> str:
+ n = self.unpack("i")
+ if n < 0:
+ raise ParseError(f"negative string length at {self.pos - 4}")
+ return self.take(2 * n).decode("utf-16-le")
+
+ # -- variants ----------------------------------------------------------------------------------
+
+ def variant(self) -> Any:
+ at = self.pos
+ code = self.unpack("B")
+ kind = code & 0x0F
+ if kind == 0x00:
+ if code not in (0x00, 0x10, 0x20):
+ raise ParseError(f"unknown stream code {code:#x} at {at}")
+ return None
+ if kind == 0x01:
+ return None
+ if kind == 0x02:
+ return True
+ if kind == 0x03:
+ return False
+ if kind == 0x04:
+ return self.unpack("B")
+ if kind == 0x05:
+ return self.unpack("h")
+ if kind == 0x06:
+ return self.unpack("i")
+ if kind == 0x07:
+ return self.unpack("f")
+ if kind == 0x08:
+ return self.unpack("d")
+ if kind == 0x09:
+ return Currency(self.unpack("q"))
+ if kind == 0x0A:
+ return Date(self.unpack("d"))
+ if kind == 0x0B:
+ return self.string()
+ if kind == 0x0C:
+ return ("error", self.unpack("i"))
+ if kind == 0x0D:
+ index = self.unpack("i")
+ if not 0 <= index < len(self.objects):
+ raise ParseError(f"undefined object reference {index} at {at}")
+ return Ref(index)
+ if kind == 0x0E:
+ return self.object(at)
+ if kind == 0x0F:
+ return self.array()
+ raise ParseError(f"unknown stream code {code:#x} at {at}") # pragma: no cover
+
+ def array(self) -> List[Any]:
+ vartype = self.unpack("B")
+ dims = self.unpack("H")
+ counts = []
+ for _ in range(dims):
+ counts.append(self.unpack("I"))
+ self.unpack("i") # lower bound
+ total = 1
+ for c in counts:
+ total *= c
+ if vartype in _ARRAY_RAW:
+ fmt = _ARRAY_RAW[vartype]
+ return list(struct.unpack(f"<{total}{fmt}", self.take(total * struct.calcsize(fmt))))
+ if vartype == 0x08:
+ return [self.string() for _ in range(total)]
+ if vartype in (0x09, 0x0C, 0x0D):
+ return [self.variant() for _ in range(total)]
+ raise ParseError(f"invalid array vartype {vartype:#x} at {self.pos}")
+
+ def object(self, at: int) -> Obj:
+ index = self.unpack("i")
+ if index != len(self.objects):
+ raise ParseError(f"invalid object definition {index} (expected {len(self.objects)}) at {at}")
+ obj = Obj(index=index, class_id=self.take(16))
+ self.objects.append(obj)
+ if obj.class_id == DICTIONARY:
+ self.dictionary(obj)
+ elif obj.class_id == LIST:
+ obj.items = [self.variant() for _ in range(self.unpack("i"))]
+ elif obj.class_id in OBJECTS:
+ obj.extension = OBJECTS[obj.class_id](self)
+ else:
+ raise ParseError(f"no reader for class {obj.class_name} at {at}")
+ return obj
+
+ def dictionary(self, obj: Obj) -> None:
+ obj.flag = self.unpack("B")
+ if obj.flag:
+ obj.extension_class_id = self.take(16)
+ if obj.flag == 1:
+ loader = EXTENSIONS.get(obj.extension_class_id)
+ if loader is None:
+ raise ParseError(f"no reader for extension {obj.extension_name} at {self.pos}")
+ obj.extension = loader(self)
+ elif obj.flag != 4:
+ raise ParseError(f"unknown dictionary flag {obj.flag} at {self.pos}")
+ count = self.unpack("i")
+ if count < 0:
+ raise ParseError(f"negative dictionary count at {self.pos - 4}")
+ obj.entries = {}
+ for _ in range(count):
+ key = self.string()
+ obj.entries[key] = self.variant()
+
+
+# -- class-specific bodies ---------------------------------------------------------------------
+
+
+def _string_list(r: Reader) -> List[str]:
+ """Data set manager: the data set names in order, as a counted list of strings."""
+ return [r.string() for _ in range(r.unpack("i"))]
+
+
+def _nothing(r: Reader) -> None:
+ """Data set: nothing of its own before the dictionary's entries."""
+ return None
+
+
+def _labware(r: Reader) -> Dict[str, Any]:
+ """Labware: per-well state, as (array variant, int32 well count) pairs.
+
+ Measured on 8-, 96- and 384-well labware: four pairs, a flag byte, six more pairs when it is
+ set, and a closing flag byte that has only been seen clear.
+ """
+
+ def pairs(n: int) -> List[Any]:
+ out = []
+ for _ in range(n):
+ values = r.variant()
+ wells = r.unpack("i")
+ if not isinstance(values, list) or len(values) != wells:
+ raise ParseError(f"labware array of {wells} wells does not hold {wells} at {r.pos}")
+ out.append(values)
+ return out
+
+ arrays = pairs(4)
+ more = r.unpack("B")
+ if more:
+ arrays += pairs(6)
+ last = r.unpack("B")
+ if last:
+ raise ParseError(f"labware closing flag {last} not seen before, at {r.pos - 1}")
+ return {"arrays": arrays}
+
+
+def _well_values(r: Reader) -> Dict[str, Any]:
+ """Well values: one value per well of a labware, named (a string), as int32 columns and int32
+ rows, then columns x rows variants. Measured on the per-well liquid names (`DataSets` /
+ `RuntimeDataSets` "Liquid") Biomek writes into the instrument file with the deck's labware after
+ a run: 24-, 96- and 8-well labware."""
+ name = r.string()
+ columns, rows = r.unpack("i"), r.unpack("i")
+ if columns < 0 or rows < 0:
+ raise ParseError(f"well values of {columns} x {rows} wells at {r.pos - 8}")
+ return {
+ "name": name,
+ "columns": columns,
+ "rows": rows,
+ "values": [r.variant() for _ in range(columns * rows)],
+ }
+
+
+def _workspace(r: Reader) -> Dict[str, Any]:
+ """Workspace root: an int32 version, then two (int32, int32, int32, int32) records. Measured."""
+ version = r.unpack("i")
+ records = [tuple(r.unpack("i") for _ in range(4)) for _ in range(2)]
+ return {"version": version, "records": records}
+
+
+def _promise(r: Reader) -> Dict[str, Any]:
+ """Promise: three doubles, then a variant, then int32 and a byte. Measured."""
+ values = [r.unpack("d") for _ in range(3)]
+ status = r.variant()
+ tail = (r.unpack("i"), r.unpack("B"))
+ return {"values": values, "status": status, "tail": tail}
+
+
+EXTENSIONS: Dict[bytes, Callable[[Reader], Any]] = {
+ DATA_SET_MANAGER: _string_list,
+ DATA_SET: _nothing,
+ LABWARE: _labware,
+ WORKSPACE: _workspace,
+ WELL_VALUES: _well_values,
+}
+
+OBJECTS: Dict[bytes, Callable[[Reader], Any]] = {
+ PROMISE: _promise,
+}
+
+
+# -- entry points ------------------------------------------------------------------------------
+
+
+def decompress(blob: bytes) -> bytes:
+ return zlib.decompress(blob[HEADER_SIZE:])
+
+
+def parse(data: bytes) -> Tree:
+ """Parse a decompressed stream completely: one int32 size, then one variant, nothing after.
+
+ Raises:
+ ParseError: for anything else.
+ """
+ r = Reader(data)
+ size = r.unpack("i")
+ if size != len(data) - 4:
+ raise ParseError(f"stream says {size} bytes, holds {len(data) - 4}")
+ root = r.variant()
+ if r.pos != len(data):
+ raise ParseError(f"{len(data) - r.pos} bytes left unparsed at {r.pos}")
+ return Tree(root=root, objects=r.objects)
+
+
+def parse_file(path: str) -> Tree:
+ with open(path, "rb") as f:
+ return parse(decompress(f.read()))
+
+
+def plain(value: Any, objects: List[Obj], inline: bool = False, _open: Optional[set] = None) -> Any:
+ """The tree as JSON-ready values: dictionaries as dicts, lists as lists, refs as {"$ref": n}.
+
+ With `inline`, a reference is replaced by the object it names, except inside that same object
+ (a cycle), where it stays {"$ref": n}.
+ """
+ _open = set() if _open is None else _open
+ if isinstance(value, Ref) and inline and value.index not in _open:
+ return plain(objects[value.index], objects, inline, _open)
+ if isinstance(value, Obj):
+ _open = _open | {value.index}
+
+ def sub(v: Any) -> Any:
+ return plain(v, objects, inline, _open)
+
+ if value.entries is not None:
+ out: Dict[str, Any] = {}
+ if value.extension_class_id is not None:
+ out["$class"] = value.extension_name
+ if value.extension is not None:
+ out["$extension"] = sub(value.extension)
+ out["$id"] = value.index
+ out.update({k: sub(v) for k, v in value.entries.items()})
+ return out
+ if value.items is not None:
+ return [sub(v) for v in value.items]
+ return {"$class": value.class_name, "$id": value.index, "$body": sub(value.extension)}
+ if isinstance(value, Ref):
+ return {"$ref": value.index}
+ if isinstance(value, Currency):
+ return value.value / 10000
+ if isinstance(value, Date):
+ return {"$date": value.days}
+ if isinstance(value, dict):
+ return {k: plain(v, objects, inline, _open) for k, v in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [plain(v, objects, inline, _open) for v in value]
+ return value
+
+
+def walk(value: Any, path: str = "") -> Iterator[Tuple[str, Any]]:
+ """Every leaf value with its path (`/Decks/Standard/Groups/...`), over a `plain` tree."""
+ if isinstance(value, dict):
+ for k, v in value.items():
+ yield from walk(v, f"{path}/{k}")
+ elif isinstance(value, list):
+ for i, v in enumerate(value):
+ yield from walk(v, f"{path}[{i}]")
+ else:
+ yield path, value
diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree_tests.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree_tests.py
new file mode 100644
index 00000000000..b6d31ef978f
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree_tests.py
@@ -0,0 +1,165 @@
+"""The variant-tree reader on streams built in the test: every value kind, objects and references,
+the class bodies it knows, and the refusals that keep a file of another format from being misread."""
+
+import struct
+import unittest
+import uuid
+
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files import variant_tree as vt
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.files_tests_support import (
+ Array,
+ Writer,
+ container,
+ stream,
+)
+
+
+def parse_root(value: object) -> object:
+ tree = vt.parse(stream(value))
+ return vt.plain(tree.root, tree.objects, inline=True)
+
+
+def without_ids(value: object) -> object:
+ if isinstance(value, dict):
+ return {k: without_ids(v) for k, v in value.items() if k != "$id"}
+ if isinstance(value, list):
+ return [without_ids(v) for v in value]
+ return value
+
+
+class ValueTests(unittest.TestCase):
+ def test_scalars_round_trip(self) -> None:
+ for value in (None, True, False, 0, -7, 2**31 - 1, 1.5, -0.001, "", "Pod1", "µL ≤ 1"):
+ with self.subTest(value=value):
+ self.assertEqual(parse_root(value), value)
+
+ def test_fixed_size_codes(self) -> None:
+ cases = [
+ (b"\x04\x2a", 42),
+ (b"\x05" + struct.pack(" None:
+ value = {"Devices": {"Pipettor1": {"Pod1": {"Name": "Pod1", "X": [1, 2.5, "three"]}}}}
+ self.assertEqual(without_ids(parse_root(value)), value)
+ paths = dict(vt.walk(without_ids(parse_root(value))))
+ self.assertEqual(paths["/Devices/Pipettor1/Pod1/X[2]"], "three")
+
+ def test_references_name_objects_defined_earlier(self) -> None:
+ shared = {"a": 1}
+ tree = vt.parse(stream([shared, vt.Ref(1)]))
+ self.assertIsInstance(tree.root.items[1], vt.Ref)
+ self.assertIs(tree.deref(tree.root.items[1]), tree.objects[1])
+ plain = vt.plain(tree.root, tree.objects, inline=True)
+ self.assertEqual(without_ids(plain), [shared, shared])
+
+ def test_arrays(self) -> None:
+ self.assertEqual(parse_root(Array(0x03, [1, -2, 3], "i")), [1, -2, 3])
+ self.assertEqual(parse_root(Array(0x05, [0.25, 2.0], "d")), [0.25, 2.0])
+ self.assertEqual(parse_root(Array(0x08, ["a", "bc"])), ["a", "bc"])
+ self.assertEqual(parse_root(Array(0x0C, [1, "x", None])), [1, "x", None])
+
+ def test_the_container_is_a_header_then_zlib(self) -> None:
+ data = stream({"k": "v"})
+ self.assertEqual(vt.decompress(container(data)), data)
+
+
+class ClassBodyTests(unittest.TestCase):
+ """The bodies of the classes besides dictionaries and lists, as `EXTENSIONS` / `OBJECTS` read
+ them, on bodies laid out as each reader states."""
+
+ @staticmethod
+ def extended(class_id: bytes, body: bytes) -> object:
+ """A dictionary with an extension of `class_id`, its body `body`, and one entry."""
+ w = Writer()
+ data = w.define(vt.DICTIONARY) + b"\x01" + class_id + body + struct.pack(" None:
+ w = Writer()
+ body = struct.pack(" None:
+ w = Writer()
+ body = w.string("Liquid") + struct.pack(" None:
+ w = Writer()
+ pair = w.variant(Array(0x05, [0.0, 1.0], "d")) + struct.pack(" None:
+ plain = self.extended(vt.WORKSPACE, struct.pack("<9i", 3, *range(8)))
+ assert isinstance(plain, dict)
+ self.assertEqual(plain["$extension"], {"version": 3, "records": [[0, 1, 2, 3], [4, 5, 6, 7]]})
+ w = Writer()
+ data = w.define(vt.PROMISE) + struct.pack("<3d", 1.0, 2.0, 3.0) + w.variant(5)
+ data += struct.pack(" bytes:
+ return struct.pack(" None:
+ good = stream({"a": 1})
+ with self.assertRaisesRegex(vt.ParseError, "stream says"):
+ vt.parse(good + b"\x00")
+ with self.assertRaisesRegex(vt.ParseError, "left unparsed"):
+ vt.parse(self.body(good[4:] + b"\x01"))
+ with self.assertRaisesRegex(vt.ParseError, "past the end"):
+ vt.parse(self.body(b"\x0b" + struct.pack(" None:
+ with self.assertRaisesRegex(vt.ParseError, "unknown stream code"):
+ vt.parse(self.body(b"\x30"))
+ with self.assertRaisesRegex(vt.ParseError, "undefined object reference"):
+ vt.parse(self.body(b"\x0d" + struct.pack(" None:
+ """Open the board and start reading its replies."""
+ await self.io.setup()
+ self._frames.reset()
+ self._reader = asyncio.create_task(self._read_loop(), name=f"{self.name} reader")
+
+ async def stop(self) -> None:
+ """Stop reading, fail every request still waiting, and release the board."""
+ if self._reader is not None:
+ self._reader.cancel()
+ try:
+ await self._reader
+ except asyncio.CancelledError:
+ pass
+ self._reader = None
+ self._fail_pending(ConnectionError(f"{self.name} stopped"))
+ await self.io.stop()
+
+ @property
+ def connected(self) -> bool:
+ return self._reader is not None and not self._reader.done()
+
+ def subscribe(self, callback: UnsolicitedCallback) -> Callable[[], None]:
+ """Call `callback` with every message the board sends unasked. Returns an unsubscribe."""
+ self._subscribers.append(callback)
+ return lambda: self._subscribers.remove(callback)
+
+ # -- requests --------------------------------------------------------------
+
+ async def send(self, request: Request, timeout: Optional[float] = None) -> Reply:
+ """Send one request and return its final reply.
+
+ Raises:
+ AceError: if the board reports an error.
+ TimeoutError: if no final reply arrives within `timeout` seconds.
+ """
+ return (await self.send_many([request], timeout=timeout))[0]
+
+ async def send_many(
+ self,
+ requests: Sequence[Request],
+ timeout: Optional[float] = None,
+ raise_errors: bool = True,
+ ) -> List[Reply]:
+ """Send requests together, packed into as few transfers as fit, and return their final
+ replies in request order. Every request is waited for before any error is raised; the first
+ error in request order is raised.
+
+ Args:
+ requests: the requests, sent in this order.
+ timeout: seconds to wait for every final reply. Defaults to `default_timeout`.
+ raise_errors: when False, replies that report an error are returned instead of raised, for
+ a caller that decides on them (such as a move refused because the axis is not homed).
+
+ Raises:
+ AceError: if `raise_errors` and the board reports an error for any of them.
+ TimeoutError: if any final reply does not arrive within `timeout` seconds.
+ """
+ if not self.connected:
+ raise ConnectionError(f"{self.name} is not set up")
+ timeout = self.default_timeout if timeout is None else timeout
+ loop = asyncio.get_running_loop()
+ entries: List[Tuple[Tuple[int, int, int, int], _Pending]] = []
+ messages = []
+ for request in requests:
+ sequence = self._next_sequence()
+ key = (request.device, request.index, sequence, request.opcode)
+ entry = _Pending(request, loop.create_future(), loop.create_future())
+ self._pending[key] = entry
+ entries.append((key, entry))
+ messages.append(request.encode(sequence))
+ try:
+ async with self._write_lock:
+ for message in messages: # one line per message, unframed, as Biomek's `ace_io` logs them
+ logger.debug("%s write %s", self.name, message.hex())
+ for transfer in pack(messages):
+ await self.io.write(transfer)
+ done, not_done = await asyncio.wait([e.done for _, e in entries], timeout=timeout)
+ if not_done:
+ late = [str(e.request) for _, e in entries if not e.done.done()]
+ raise TimeoutError(f"{self.name}: no reply within {timeout} s to {', '.join(late)}")
+ replies = [replace(e.done.result(), related=tuple(e.related)) for _, e in entries]
+ if raise_errors:
+ for (_, entry), reply in zip(entries, replies):
+ self._raise_for(entry, reply)
+ return replies
+ finally:
+ for key, entry in entries:
+ self._pending.pop(key, None)
+ for future in (entry.done, entry.accepted):
+ if not future.done():
+ future.cancel()
+
+ def _raise_for(self, entry: _Pending, reply: Reply) -> None:
+ """Raise the reply's error, with the errors of the axes a failed Move All names."""
+ if reply.error_code is None:
+ return
+ error = ace_error(
+ reply.error_code, reply.device_error, str(entry.request), reply.device, reply.index
+ )
+ causes = [r for r in entry.related if r.error_code is not None]
+ if causes:
+ error.axis_errors = [
+ ace_error(
+ r.error_code or 0,
+ r.device_error,
+ f"device 0x{r.device:02X} index {r.index}",
+ r.device,
+ r.index,
+ )
+ for r in causes
+ ]
+ error.args = (str(error) + "; " + "; ".join(str(e) for e in error.axis_errors),)
+ raise error
+
+ def _next_sequence(self) -> int:
+ """The next free sequence number, 1-255 then 1 again; 0 is the board's own."""
+ in_use = {key[2] for key in self._pending}
+ for _ in range(255):
+ self._sequence = self._sequence % 255 + 1
+ if self._sequence not in in_use:
+ return self._sequence
+ raise RuntimeError(f"{self.name}: all 255 sequence numbers are waiting for replies")
+
+ # -- replies ---------------------------------------------------------------
+
+ async def _read_loop(self) -> None:
+ while True:
+ try:
+ data = await self.io.read(timeout=1, size=IN_PACKET_SIZE)
+ except TimeoutError:
+ continue
+ except asyncio.CancelledError:
+ raise
+ except Exception as e: # the link is gone; nobody will answer what is waiting
+ logger.error("%s: read failed: %s", self.name, e)
+ self._fail_pending(ConnectionError(f"{self.name}: read failed: {e}"))
+ return
+ try:
+ messages = self._frames.feed(data)
+ except FrameError as e:
+ logger.error("%s: %s", self.name, e)
+ continue
+ for message in messages:
+ self._dispatch(message)
+
+ def _dispatch(self, message: bytes) -> None:
+ logger.debug("%s read %s", self.name, message.hex())
+ try:
+ reply = Reply.parse(message)
+ except ValueError as e:
+ logger.error("%s: %s", self.name, e)
+ return
+ if reply.unsolicited:
+ self._deliver_unsolicited(reply)
+ return
+ entry = self._pending.get(reply.key)
+ if entry is None:
+ related = self._pending_with_sequence(reply.sequence, reply.opcode)
+ if related is not None:
+ related.related.append(reply)
+ else:
+ logger.warning("%s: reply to no waiting request: %s", self.name, message.hex())
+ return
+ if reply.status == Status.ACCEPTED and reply.error_code is None:
+ if not entry.accepted.done():
+ entry.accepted.set_result(reply)
+ return
+ if not entry.done.done():
+ entry.done.set_result(reply)
+
+ def _pending_with_sequence(self, sequence: int, opcode: int) -> Optional[_Pending]:
+ for key, entry in self._pending.items():
+ if key[2] == sequence and key[3] == opcode:
+ return entry
+ return None
+
+ def _deliver_unsolicited(self, reply: Reply) -> None:
+ if (reply.device, reply.opcode) == SAGIAN_CAN:
+ # A message the board saw on its SAGIAN CAN bus, passed up: normal when a success or a
+ # request (see `describe_sagian_can`), flagged otherwise.
+ text, normal = describe_sagian_can(reply.data)
+ if normal:
+ logger.debug("%s: SAGIAN CAN %s (forwarded, normal)", self.name, text)
+ else:
+ logger.info("%s: SAGIAN CAN %s: a status not seen in normal operation", self.name, text)
+ elif (routine := describe_routine_unsolicited(reply)) is not None:
+ logger.debug("%s: %s (routine)", self.name, routine)
+ elif reply.status in (Status.EMERGENCY, Status.EVENT) or reply.error_code is not None:
+ logger.info("%s: unsolicited %s", self.name, reply)
+ for callback in list(self._subscribers):
+ try:
+ callback(reply)
+ except Exception:
+ logger.exception("%s: subscriber failed on %s", self.name, reply)
+
+ def _fail_pending(self, error: Exception) -> None:
+ for entry in self._pending.values():
+ if not entry.done.done():
+ entry.done.set_exception(error)
+ self._pending.clear()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/board_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/board_tests.py
new file mode 100644
index 00000000000..f625baa7680
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/board_tests.py
@@ -0,0 +1,183 @@
+"""AceBoard against a fake board: matching, two-stage replies, unsolicited messages, errors."""
+
+import asyncio
+import unittest
+from typing import Callable, List, Optional
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import (
+ InterlockTrippedError,
+ MotionError,
+ NotHomedError,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.framing import frame, split
+from pylabrobot.io.usb import USB
+
+Handler = Callable[[bytes], List[bytes]]
+
+
+def done(request: bytes, payload: bytes = b"") -> bytes:
+ return request[:5] + b"\x02\x00" + payload
+
+
+def accepted(request: bytes) -> bytes:
+ return request[:5] + b"\x01\x00"
+
+
+def recorder(into: List[bytes], answer: Handler = lambda m: []) -> Handler:
+ """A handler that keeps every request in `into`, then answers with `answer`."""
+
+ def handler(message: bytes) -> List[bytes]:
+ into.append(message)
+ return answer(message)
+
+ return handler
+
+
+def answer_done(message: bytes) -> List[bytes]:
+ return [done(message)]
+
+
+class FakeAceUSB(USB):
+ """A board on the far side of the USB link: records transfers, answers through `handler`, and
+ sends replies in 16-byte packets as a board does."""
+
+ def __init__(self, handler: Optional[Handler] = None):
+ super().__init__(0x0AB5, 0xACE0, "fake ACE board")
+ self.handler: Handler = handler or answer_done
+ self.transfers: List[bytes] = []
+ self._packets: "asyncio.Queue[bytes]" = asyncio.Queue()
+
+ async def setup(self, empty_buffer=True):
+ pass
+
+ async def stop(self):
+ pass
+
+ async def write(self, data: bytes, timeout: Optional[float] = None):
+ self.transfers.append(data)
+ for message in split(data):
+ for reply in self.handler(message):
+ self.push(reply)
+
+ def push(self, message: bytes) -> None:
+ framed = frame(message)
+ for i in range(0, len(framed), 16):
+ self._packets.put_nowait(framed[i : i + 16])
+
+ async def read(self, timeout=None, size=None, endpoint=None) -> bytes:
+ try:
+ return await asyncio.wait_for(self._packets.get(), timeout=0.01)
+ except asyncio.TimeoutError:
+ raise TimeoutError("no packet") from None
+
+
+class BoardTests(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self) -> None:
+ self.usb = FakeAceUSB()
+ self.board = AceBoard(io=self.usb, default_timeout=1)
+ await self.board.setup()
+
+ async def asyncTearDown(self) -> None:
+ await self.board.stop()
+
+ async def test_simple_request(self) -> None:
+ self.usb.handler = lambda m: [done(m, b"\x80\x00")]
+ reply = await self.board.send(p.get_module_id())
+ self.assertEqual(p.parse_module_id(reply.payload).type, "chassis")
+ self.assertEqual(self.usb.transfers, [frame(p.get_module_id().encode(1))])
+
+ async def test_replies_out_of_order_match_their_requests(self) -> None:
+ held: List[bytes] = []
+ self.usb.handler = recorder(held)
+ task = asyncio.create_task(
+ self.board.send_many([p.get_current_position(p.Device.MOTOR, axis) for axis in range(1, 9)])
+ )
+ while len(held) < 8:
+ await asyncio.sleep(0)
+ for message in reversed(held):
+ self.usb.push(done(message, message[1].to_bytes(4, "little")))
+ replies = await task
+ self.assertEqual([p.parse_s32(r.payload) for r in replies], list(range(1, 9)))
+ self.assertEqual(len(self.usb.transfers), 1) # packed together
+
+ async def test_two_stage_reply_waits_for_done(self) -> None:
+ held: List[bytes] = []
+ self.usb.handler = recorder(held, lambda m: [accepted(m)])
+ task = asyncio.create_task(self.board.send(p.move_all(5000)))
+ await asyncio.sleep(0.05)
+ self.assertFalse(task.done())
+ self.usb.push(done(held[0]))
+ self.assertEqual((await task).status, p.Status.DONE)
+
+ async def test_unsolicited_messages_go_to_subscribers_between_replies(self) -> None:
+ seen: List[p.Reply] = []
+ self.board.subscribe(seen.append)
+ host_alive = bytes.fromhex("0000000040FE00")
+ emcy = bytes.fromhex("0000000031FF007E0010013704110000")
+ self.usb.handler = lambda m: [host_alive, emcy, done(m)]
+ await self.board.send(p.get_module_serial_number())
+ await asyncio.sleep(0.05)
+ self.assertEqual([(r.device, r.opcode) for r in seen], [p.HOST_ALIVE, p.EMCY])
+ self.assertEqual(p.parse_emcy(seen[1].data).device_error, 0x0437)
+
+ async def test_error_status_raises(self) -> None:
+ self.usb.handler = lambda m: [m[:5] + b"\x00\x32"]
+ with self.assertRaises(NotHomedError):
+ await self.board.send(p.set_motor_move_parameters(1, 0, 1, 1, 1))
+
+ async def test_failed_move_all_raises_with_its_axes(self) -> None:
+ def handler(m: bytes) -> List[bytes]:
+ axis = bytes([0x11, 0x0A, 0x00, m[3], 0x50, 0x02, 0x3C, 0x00, 0x01, 0x00, 0x00])
+ return [accepted(m), axis, m[:5] + b"\x02\x38"]
+
+ self.usb.handler = handler
+ with self.assertRaises(MotionError) as ctx:
+ await self.board.send(p.move_all(5000))
+ self.assertEqual([e.device_error for e in ctx.exception.axis_errors], [0x100])
+ self.assertIn("motion error window exceeded", str(ctx.exception))
+
+ async def test_interlock_on_completion(self) -> None:
+ self.usb.handler = lambda m: [accepted(m), m[:5] + b"\x02\x0f\x07\x04\x00\x00"]
+ with self.assertRaises(InterlockTrippedError) as ctx:
+ await self.board.send(p.move(1, 30000))
+ self.assertEqual(ctx.exception.device_error, 0x407)
+
+ async def test_timeout_releases_the_sequence(self) -> None:
+ self.usb.handler = lambda m: []
+ with self.assertRaises(TimeoutError):
+ await self.board.send(p.get_module_id(), timeout=0.05)
+ self.assertEqual(self.board._pending, {})
+
+ async def test_sequence_wraps_past_zero_and_skips_waiting_ones(self) -> None:
+ self.board._sequence = 254
+ seen_requests: List[bytes] = []
+ self.usb.handler = recorder(seen_requests, lambda m: [done(m)])
+ for _ in range(3):
+ await self.board.send(p.get_module_id())
+ self.assertEqual([m[3] for m in seen_requests], [255, 1, 2])
+
+ held: List[bytes] = []
+ self.usb.handler = recorder(held)
+ waiting = asyncio.create_task(self.board.send(p.get_module_id())) # takes 3
+ await asyncio.sleep(0)
+ self.board._sequence = 2
+ self.usb.handler = recorder(seen_requests, lambda m: [done(m)])
+ await self.board.send(p.get_module_serial_number())
+ self.assertEqual(seen_requests[-1][3], 4)
+ self.usb.push(done(held[0]))
+ await waiting
+
+ async def test_stop_fails_waiting_requests(self) -> None:
+ self.usb.handler = lambda m: []
+ task = asyncio.create_task(self.board.send(p.get_module_id()))
+ await asyncio.sleep(0.02)
+ await self.board.stop()
+ with self.assertRaises(ConnectionError):
+ await task
+ await self.board.setup() # so tearDown can stop it again
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py
new file mode 100644
index 00000000000..fed087c574c
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py
@@ -0,0 +1,585 @@
+"""What the driver knows about an instrument: facts only (STAR design.md P3).
+
+Two kinds:
+
+- **What the boards answer** about themselves at setup (`ModuleConfiguration`, `BoardInfo`).
+- **What they cannot answer**, declared per instrument (`DeviceConfiguration`):
+ - the motor tables loaded into the boards after every power-up;
+ - per pod, the counts conversions, travel limits, geometry and settings that Biomek keeps on
+ the host side.
+
+ One JSON file per instrument, made only by `DeviceConfiguration.from_biomek` from the
+ instrument's two Biomek sources (`biomek_files/`), and given to the driver by path; no
+ instrument's own ships with the driver (the generic one in `defaults/`, anonymized, is for
+ simulation):
+ - Biomek's instrument file (`.bif`): the pods, the deck's calibrated positions and its layout;
+ - the Master Controller's instrument record: the motor tables (with each instrument's measured
+ hysteresis) and the modules' serial numbers.
+
+ `sources` records, per source, where it was read, when, and a fingerprint of exactly the values
+ taken from it. Loading refuses a file whose values no longer match its fingerprints (changed
+ after it was imported), and a live session refuses one whose sources have changed since
+ (`check_sources`).
+"""
+
+import copy
+import hashlib
+import json
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Literal, Optional, Tuple, Union
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.motors import MotorTables
+from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import HardwareVersion, ModuleId
+
+# The firmware this driver has been run against (one instrument, 2026-10-24 through 2026-11-10):
+# every motion board and module the same image, and the other boards' application versions
+# (chassis 0.2.4, SAGIAN Motion 0.3.14, LLS 0.7.8, syringe pump 5.0.9). The Master Controller
+# flashes the boards when it brings other firmware, which would change what the boards answer.
+TESTED_FIRMWARE_IMAGES = {(0x6D2DDB78, 266436)}
+TESTED_APPLICATION_VERSIONS = {"0.2.4", "0.3.14", "0.7.8", "5.0.9"}
+
+
+@dataclass
+class BoardInfo:
+ """One board inside a module, as the module reports it."""
+
+ index: int
+ hardware: HardwareVersion
+ serial_number: Optional[str] = None
+ application_version: Optional[str] = None
+ application_crc: Optional[int] = None
+ application_length: Optional[int] = None
+
+
+@dataclass
+class ModuleConfiguration:
+ """One ACE module (the chassis, or an arm): its identity, its boards, and its inputs."""
+
+ module_id: ModuleId
+ usb_serial_number: Optional[str]
+ serial_number: str
+ hardware: HardwareVersion
+ application_crc: int
+ application_length: int
+ device_counts: Dict[int, int]
+ boards: List[BoardInfo] = field(default_factory=list)
+ analog_inputs: Dict[int, str] = field(default_factory=dict)
+ analog_units: Dict[int, str] = field(default_factory=dict)
+ digital_inputs: Dict[int, str] = field(default_factory=dict)
+ digital_outputs: Dict[int, str] = field(default_factory=dict)
+
+ def untested_firmware(self) -> List[str]:
+ """What this module runs that the driver has not been run against: one line per image or
+ version, empty when everything is tested."""
+ found = []
+ if (self.application_crc, self.application_length) not in TESTED_FIRMWARE_IMAGES:
+ found.append(
+ f"module image CRC {self.application_crc:#010x}, {self.application_length} bytes"
+ )
+ for b in self.boards:
+ image = (b.application_crc, b.application_length)
+ if b.application_crc is not None and image not in TESTED_FIRMWARE_IMAGES:
+ found.append(
+ f"board {b.index} image CRC {b.application_crc:#010x}, {b.application_length} bytes"
+ )
+ if (
+ b.application_version is not None
+ and b.application_version not in TESTED_APPLICATION_VERSIONS
+ ):
+ found.append(f"board {b.index} application {b.application_version}")
+ return found
+
+
+# -- declared per instrument -------------------------------------------------------------------------
+
+Side = Literal["left", "right"]
+
+
+@dataclass(frozen=True)
+class AxisConversion:
+ """How Biomek turns a value into counts for one axis or quantity: `counts = (value + offset) x
+ const`, rounded. `unit` is what `value` is in: Biomek's own units, `cm`, `deg` or `uL`.
+
+ Read from the instrument file's `CmdGen/Conversion` (`Const`, `Offset`). Checked on
+ this instrument against positions it logged:
+ - the Multichannel's park GR, 90 deg, is -175,443 counts;
+ - its rest Z, 39.763 cm, is -256 counts;
+ - the Span-8 Z park, 39.1079 cm on Z1, is 9,029 counts.
+ """
+
+ const: float
+ offset: float
+ unit: str
+
+ def to_counts(self, value: float) -> int:
+ return round((value + self.offset) * self.const)
+
+ def to_value(self, counts: int) -> float:
+ return counts / self.const - self.offset
+
+
+@dataclass(frozen=True)
+class PodGeometry:
+ """A pod's dimensions as Biomek's collision model uses them, in cm.
+
+ From the instrument file's per-device pod entry. That entry, not the pod type's defaults under
+ `HardwareSetupInfo/PodTypes`, is what reproduces the travel Biomek logged:
+ - BridgeXSpan is 39.0154 here, 12.7 in the type defaults;
+ - the bridges touch at left X + |right X| = 250,807 counts, and the most Biomek ever commanded
+ was 250,678.
+
+ The optional fields are absent on a pod type that has no such part.
+ """
+
+ bridge_x_span: float
+ bridge_to_head_x_offset: float
+ mandrel1_x_offset: float
+ mandrel1_y_offset: float
+ mandrel_x_spacing: float
+ mandrel_y_spacing: float
+ avoidance_margin: float
+ pod_x_span: float
+ pod_y_span: float
+ gripper_x_offset: float
+ gripper_y_offset: float
+ gripper_z_offset: float
+ frame_safety_left: float
+ frame_safety_right: float
+ additional_safe_height: float
+ additional_safe_height_gripper: float
+ mandrels_x: Optional[int] = None
+ mandrels_y: Optional[int] = None
+ sub_mandrel_safe_height: Optional[float] = None
+
+
+@dataclass(frozen=True)
+class Obstacle:
+ """A fixed obstacle on the deck, as Biomek keeps it per pod (`Obstacles` in the instrument
+ file): a box in Biomek's frame (cm; Y towards the front, Z up from the deck surface),
+ a bound that is None open on that side, widened by `buffer`. Walls (the shields, the towers, the
+ light curtain) have no Z bounds; the pump bank is a floor up to `z2`; the I-beam a ceiling from
+ `z1`."""
+
+ name: str
+ buffer: float = 0.0
+ x1: Optional[float] = None
+ x2: Optional[float] = None
+ y1: Optional[float] = None
+ y2: Optional[float] = None
+ z1: Optional[float] = None
+ z2: Optional[float] = None
+
+
+# The settings the driver takes from a pod's entry in the instrument file, never assumed: a pod
+# whose entry lacks one is refused (`PodConfiguration`). Every pod's; a gripper's; each pod type's.
+POD_SETTINGS: Tuple[str, ...] = ()
+GRIPPER_SETTINGS: Tuple[str, ...] = ("GripperSqueezeForce",)
+TYPE_SETTINGS: Dict[str, Tuple[str, ...]] = {
+ "span8": ("ProbeSize",),
+ "multichannel": (
+ "HeadBodyXSpan",
+ "HeadBodyYSpan",
+ ),
+}
+
+
+def required_settings(module_type: str, gripper: bool) -> Tuple[str, ...]:
+ """The settings a pod of `module_type` (with a gripper or not) must have in its entry."""
+ return (
+ *POD_SETTINGS,
+ *(GRIPPER_SETTINGS if gripper else ()),
+ *TYPE_SETTINGS.get(module_type, ()),
+ )
+
+
+@dataclass
+class PodConfiguration:
+ """One pod's facts the boards do not hold.
+
+ - `conversion`: per axis or quantity, keyed by Biomek's own names (`X`, `Y`, `Z`, `D`, `GY`,
+ `GG`, `GZ`, `GR`; on a Span-8 also `S` for the span, `Z1`..`Z8`, `D1`..`D8`).
+ - `limits`: each axis's travel in those units, `(lowest, highest)`.
+ - `park`: Biomek's park location.
+ - `settings`: every other scalar Biomek keeps for the pod, and the Span-8's per-probe lists
+ (`LoadingOffsets`, `BrokenTips`) (tip loading, safe heights, speeds,
+ gripper squeeze) under its own name, for the features that will use them.
+ - `gripper_model`: the gripper's dimensions, as Biomek nests them; empty for a pod with no
+ gripper.
+ - `module_serial_number`: the serial number the pod's module reports, which ties these facts to
+ one module (`BiomekI7Driver.discover` checks it), from the Master Controller's record; None in
+ the generic configuration.
+ """
+
+ component: str
+ module_type: str
+ side: Side
+ conversion: Dict[str, AxisConversion]
+ limits: Dict[str, Tuple[float, float]]
+ geometry: PodGeometry
+ park: Dict[str, float] = field(default_factory=dict)
+ settings: Dict[str, Any] = field(default_factory=dict)
+ gripper_model: Dict[str, Any] = field(default_factory=dict)
+ obstacles: List[Obstacle] = field(default_factory=list)
+ source: str = ""
+ module_serial_number: Optional[str] = None
+
+ def __post_init__(self) -> None:
+ missing = [
+ k
+ for k in required_settings(self.module_type, bool(self.gripper_model))
+ if k not in self.settings
+ ]
+ if missing:
+ raise ValueError(
+ f"{self.component}: the instrument file's entry for this pod has no {', '.join(missing)}; "
+ "the driver takes these from it and never assumes them"
+ )
+
+ def to_counts(self, axis: str, value: float) -> int:
+ """A value in Biomek's units for `axis` (see `conversion`) as counts.
+
+ Raises:
+ ValueError: for an axis with no conversion.
+ """
+ return self._conversion(axis).to_counts(value)
+
+ def to_value(self, axis: str, counts: int) -> float:
+ """Counts on `axis` as a value in Biomek's units for it."""
+ return self._conversion(axis).to_value(counts)
+
+ def probe_spacing(self) -> float:
+ """A Span-8's probes' spacing at their narrowest (cm): the span axis's zero shared out between
+ the eight (`S` counts from that span, and each probe's Y counts from its narrowest place), or
+ `ProbeSize` without a span axis."""
+ if "S" in self.conversion:
+ return -self.conversion["S"].offset / 7
+ return float(self.settings["ProbeSize"])
+
+ def probe_y(self, probe: int, counts: int) -> float:
+ """Span-8 probe `probe`'s (1-8) Y in cm from its `Y` counts: the `Y` conversion is
+ probe 1's, and each next probe's counts start one narrowest spacing further on."""
+ return self.to_value("Y", counts) + (probe - 1) * self.probe_spacing()
+
+ def _conversion(self, axis: str) -> AxisConversion:
+ if axis not in self.conversion:
+ raise ValueError(
+ f"{self.component} has no conversion for {axis!r}; has {sorted(self.conversion)}"
+ )
+ return self.conversion[axis]
+
+
+@dataclass(frozen=True)
+class DeckPosition:
+ """A deck position as Biomek calibrated it, in Biomek's frame (cm; Y towards the front, Z up
+ from the deck surface): a corner per pod, by Biomek's pod number, and the position's spans.
+
+ Each pod moves to a position relative to its own corner: corner n is the one that shifts when
+ pod n's deck framing changes (`ShiftDeck` applied to `X`/`Y`/`Z`). `framed[n]` says
+ how corner n was obtained: `Position` (framed at this position) or `Deck` (from the deck's framing).
+ """
+
+ corners: Dict[int, Tuple[float, float, float]]
+ x_span: float
+ y_span: float
+ framed: Dict[int, str] = field(default_factory=dict)
+
+ def corner(self, pod_number: int) -> Tuple[float, float, float]:
+ """Raises:
+ ValueError: for a pod with no corner here.
+ """
+ if pod_number not in self.corners:
+ raise ValueError(f"no corner for pod {pod_number}; have {sorted(self.corners)}")
+ return self.corners[pod_number]
+
+
+@dataclass(frozen=True)
+class AlpPlacement:
+ """One ALP of a deck layout, as an instrument file places it (`Decks//Groups/`): its
+ name and Biomek type, the pin column of its left pins and the pin row of its front pins, the
+ names of its positions, and the X Biomek has its left edge at (`X1`, cm), which checks the
+ column."""
+
+ name: str
+ alp_type: str
+ column: int
+ row: int
+ positions: Tuple[str, ...]
+ x1: Optional[float] = None
+
+
+SOURCES = ("instrument_file", "master_controller")
+
+
+def source_parts(data: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
+ """A serialized configuration's values split by the source each comes from (`SOURCES`)."""
+ pods = data.get("pods", {})
+ return {
+ "instrument_file": {
+ "instrument_serial_number": data.get("instrument_serial_number"),
+ "pods": {
+ side: {k: v for k, v in pod.items() if k != "module_serial_number"}
+ for side, pod in pods.items()
+ },
+ "deck_positions": data.get("deck_positions", {}),
+ "deck_layout": data.get("deck_layout", []),
+ },
+ "master_controller": {
+ "chassis_serial_number": data.get("chassis_serial_number"),
+ "module_serial_numbers": {
+ side: pod.get("module_serial_number") for side, pod in pods.items()
+ },
+ "modules": data.get("modules", {}),
+ },
+ }
+
+
+def fingerprint(value: Any) -> str:
+ """A digest of `value`'s canonical JSON: equal values, equal fingerprints."""
+ text = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
+ return "sha256:" + hashlib.sha256(text.encode("ascii")).hexdigest()
+
+
+def differences(old: Any, new: Any, path: str = "") -> List[str]:
+ """Where two JSON values differ, one line per leaf (`pods/left/limits/X: [..] -> [..]`)."""
+ if isinstance(old, dict) and isinstance(new, dict):
+ lines = []
+ for key in sorted(set(old) | set(new), key=str):
+ sub = f"{path}/{key}" if path else str(key)
+ if key not in old:
+ lines.append(f"{sub}: added")
+ elif key not in new:
+ lines.append(f"{sub}: removed")
+ else:
+ lines += differences(old[key], new[key], sub)
+ return lines
+ if isinstance(old, list) and isinstance(new, list) and len(old) == len(new):
+ return [
+ line for i, (a, b) in enumerate(zip(old, new)) for line in differences(a, b, f"{path}[{i}]")
+ ]
+ return [] if old == new else [f"{path}: {old!r} -> {new!r}"]
+
+
+@dataclass(frozen=True)
+class SourcesCheck:
+ """How a configuration's sources compare with it now (`DeviceConfiguration.check_sources`):
+ `changed` lists each value that differs, `unavailable` each source that could not be found."""
+
+ changed: List[str]
+ unavailable: List[str]
+
+
+@dataclass
+class DeviceConfiguration:
+ """Everything declared about one instrument: its motor tables and its pods.
+
+ `chassis_serial_number` and each pod's `module_serial_number` tie the file to the instrument it
+ describes: a live session refuses a file whose serial numbers are not the instrument's
+ (`BiomekI7Driver.discover`). `generic` marks a file that describes no instrument in particular
+ (the package's default, for simulation; `anonymized`): it carries no serial numbers and no
+ measured hysteresis, and a live session refuses it. `instrument_serial_number` is the instrument
+ file's own, for information only. `sources`: per source (`SOURCES`), its `fingerprint`, and for
+ an instrument's own file where (`path`, `kind`) and when (`read_at`) it was read."""
+
+ chassis_serial_number: Optional[str]
+ instrument_serial_number: Optional[str]
+ modules: Dict[str, Any]
+ pods: Dict[Side, PodConfiguration]
+ sources: Dict[str, Dict[str, str]] = field(default_factory=dict)
+ # The default deck's positions by Biomek's name (`P1`, `TL1`), as calibrated; empty if not
+ # imported.
+ deck_positions: Dict[str, DeckPosition] = field(default_factory=dict)
+ generic: bool = False
+ # The default deck's ALPs, as the instrument file places them; empty if not imported.
+ deck_layout: List[AlpPlacement] = field(default_factory=list)
+
+ @property
+ def motor_tables(self) -> MotorTables:
+ return MotorTables.from_dict(self.modules)
+
+ def pod(self, side: Side) -> PodConfiguration:
+ """Raises:
+ ValueError: if nothing is declared for that side.
+ """
+ if side not in self.pods:
+ raise ValueError(f"no pod declared on the {side}; declared: {sorted(self.pods)}")
+ return self.pods[side]
+
+ @classmethod
+ def from_biomek(
+ cls,
+ bif: Union[str, Path],
+ master_controller_db: Optional[Union[str, Path]] = None,
+ master_controller_record: Optional[Union[str, Path]] = None,
+ chassis_serial_number: Optional[str] = None,
+ ) -> "DeviceConfiguration":
+ """An instrument's declared configuration, from its Biomek files: the only way one is made.
+
+ Args:
+ bif: Biomek's instrument file (on the instrument's computer,
+ `C:\\Users\\Public\\Documents\\Biomek5\\Biomek_i7.bif`).
+ master_controller_db: the Master Controller's database (`C:\\ProgramData\\Beckman
+ Coulter\\Biomek Master Controller\\Log.db3`), read-only.
+ master_controller_record: instead of the database, a text file holding its instrument
+ record (`biomek_files.master_controller.write_record`).
+ chassis_serial_number: which instrument's record, when the database holds more than one.
+
+ Raises:
+ ValueError: for files that do not describe one consistent instrument (see
+ `biomek_files.importer`).
+ """
+ from pylabrobot.beckman_coulter.biomek_i7.biomek_files.importer import import_configuration
+
+ return import_configuration(
+ bif,
+ master_controller_db=master_controller_db,
+ master_controller_record=master_controller_record,
+ chassis_serial_number=chassis_serial_number,
+ )
+
+ def check_sources(self) -> SourcesCheck:
+ """Read this configuration's sources again (read-only) and say what has changed since it was
+ imported, and which sources cannot be found here."""
+ from pylabrobot.beckman_coulter.biomek_i7.biomek_files.importer import check_sources
+
+ return check_sources(self)
+
+ def fingerprints(self) -> Dict[str, str]:
+ """The fingerprint of the values taken from each source, as they are now."""
+ parts = source_parts(self.to_dict())
+ return {name: fingerprint(parts[name]) for name in SOURCES}
+
+ def unrecorded_changes(self) -> List[str]:
+ """The sources whose values no longer match the fingerprints recorded at import: changed after
+ the file was made, by hand or by anything but `from_biomek`."""
+ now = self.fingerprints()
+ return [name for name in SOURCES if self.sources.get(name, {}).get("fingerprint") != now[name]]
+
+ def anonymized(self) -> "DeviceConfiguration":
+ """This configuration as a generic Biomek i7: every serial number removed (any key naming one,
+ at any depth), the measured hysteresis zeroed, `generic` set, and the sources reduced to their
+ fingerprints (no path or date)."""
+ data = self.to_dict()
+
+ def scrub(value: Any) -> Any:
+ if isinstance(value, dict):
+ return {k: None if "serial" in k.lower() else scrub(v) for k, v in value.items()}
+ if isinstance(value, list):
+ return [scrub(v) for v in value]
+ return value
+
+ data = scrub(data)
+ for axes in data["modules"].values():
+ for axis in axes:
+ axis["hysteresis"] = 0
+ data["generic"] = True
+ data["sources"] = {}
+ generic = DeviceConfiguration.from_dict(data)
+ generic.sources = {name: {"fingerprint": f} for name, f in generic.fingerprints().items()}
+ return generic
+
+ @classmethod
+ def load(cls, path: Union[str, Path]) -> "DeviceConfiguration":
+ """An instrument's declared configuration, from the file `from_biomek` made and `save` wrote.
+
+ Raises:
+ ValueError: if its values no longer match the fingerprints recorded at import: it was
+ changed afterwards. Make it again with `from_biomek`.
+ """
+ with open(path, encoding="utf-8") as fh:
+ config = cls.from_dict(json.load(fh))
+ changed = config.unrecorded_changes()
+ if changed:
+ raise ValueError(
+ f"{path}: the values from {' and '.join(changed)} are not the ones imported (changed "
+ "after import, or not made by `DeviceConfiguration.from_biomek`); import it again from "
+ "the instrument's Biomek files"
+ )
+ return config
+
+ def save(self, path: Union[str, Path], indent: Optional[int] = 2) -> None:
+ """Write it as `load` reads it; `indent` as `json.dump`'s (None: one line)."""
+ Path(path).write_text(json.dumps(self.to_dict(), indent=indent) + "\n", encoding="utf-8")
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "DeviceConfiguration":
+ pods: Dict[Side, PodConfiguration] = {}
+ for side, p in data.get("pods", {}).items():
+ pods[side] = PodConfiguration(
+ component=p["component"],
+ module_type=p["module_type"],
+ side=side,
+ conversion={k: AxisConversion(**v) for k, v in p["conversion"].items()},
+ limits={k: (v[0], v[1]) for k, v in p["limits"].items()},
+ geometry=PodGeometry(**p["geometry"]),
+ park=dict(p.get("park", {})),
+ settings=dict(p.get("settings", {})),
+ gripper_model=dict(p.get("gripper_model", {})),
+ obstacles=[Obstacle(**o) for o in p.get("obstacles", [])],
+ source=p.get("source", ""),
+ module_serial_number=p.get("module_serial_number"),
+ )
+ positions = {
+ name: DeckPosition(
+ corners={int(n): (c[0], c[1], c[2]) for n, c in p["corners"].items()},
+ x_span=p["x_span"],
+ y_span=p["y_span"],
+ framed={int(n): v for n, v in p.get("framed", {}).items()},
+ )
+ for name, p in data.get("deck_positions", {}).items()
+ }
+ return cls(
+ chassis_serial_number=data.get("chassis_serial_number"),
+ instrument_serial_number=data.get("instrument_serial_number"),
+ modules=data["modules"],
+ pods=pods,
+ sources=copy.deepcopy(data.get("sources", {})),
+ deck_positions=positions,
+ generic=bool(data.get("generic", False)),
+ deck_layout=[
+ AlpPlacement(
+ name=a["name"],
+ alp_type=a["alp_type"],
+ column=a["column"],
+ row=a["row"],
+ positions=tuple(a["positions"]),
+ x1=a.get("x1"),
+ )
+ for a in data.get("deck_layout", [])
+ ],
+ )
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "generic": self.generic,
+ "chassis_serial_number": self.chassis_serial_number,
+ "instrument_serial_number": self.instrument_serial_number,
+ "sources": self.sources,
+ "pods": {
+ side: {
+ "component": p.component,
+ "module_type": p.module_type,
+ "module_serial_number": p.module_serial_number,
+ "source": p.source,
+ "conversion": {k: asdict(c) for k, c in p.conversion.items()},
+ "limits": {k: list(v) for k, v in p.limits.items()},
+ "geometry": {k: v for k, v in asdict(p.geometry).items() if v is not None},
+ "park": p.park,
+ "settings": p.settings,
+ "gripper_model": p.gripper_model,
+ "obstacles": [{k: v for k, v in asdict(o).items() if v is not None} for o in p.obstacles],
+ }
+ for side, p in self.pods.items()
+ },
+ "deck_positions": {
+ name: {
+ "corners": {str(n): list(c) for n, c in p.corners.items()},
+ "x_span": p.x_span,
+ "y_span": p.y_span,
+ "framed": {str(n): v for n, v in p.framed.items()},
+ }
+ for name, p in self.deck_positions.items()
+ },
+ "deck_layout": [{**asdict(a), "positions": list(a.positions)} for a in self.deck_layout],
+ "modules": self.modules,
+ }
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration_tests.py
new file mode 100644
index 00000000000..d87feb86824
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration_tests.py
@@ -0,0 +1,184 @@
+"""The declared configuration: how it converts, how it is kept, and how discovery checks it against
+the boards. On the package's generic configuration, whose physical values are one instrument's."""
+
+import asyncio
+import dataclasses
+import json
+import os
+import tempfile
+import unittest
+
+from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_CONFIGURATION
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration
+from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import (
+ generic_configuration,
+ generic_driver,
+ sealed,
+)
+
+MASTER_LOGGER = "pylabrobot.beckman_coulter.biomek_i7.driver.master"
+
+
+class DeclaredConfigurationTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.config = generic_configuration()
+ self.left, self.right = self.config.pod("left"), self.config.pod("right")
+
+ def test_pods_as_the_instrument_file_has_them(self) -> None:
+ self.assertEqual((self.left.component, self.left.module_type), ("MC_1", "multichannel"))
+ self.assertEqual((self.right.component, self.right.module_type), ("SPAN8_2", "span8"))
+ self.assertEqual(self.left.geometry.bridge_x_span, 39.0154)
+ self.assertEqual(self.right.geometry.bridge_x_span, 25.7204)
+ self.assertAlmostEqual(self.left.conversion["X"].offset, -10.519)
+ self.assertAlmostEqual(self.right.conversion["X"].offset, -146.40669375)
+ self.assertEqual(self.left.settings["TipLoadForceLimitSlope"], 2150)
+
+ def test_conversions_give_the_counts_biomek_logged(self) -> None:
+ # Targets Biomek's instrument file holds, and the counts its logs show it sent for them.
+ self.assertEqual(self.left.to_counts("GR", self.left.park["GR"]), -175443) # the park's GR
+ self.assertEqual(self.left.to_counts("D", 0.0), 43176) # the plunger's home
+ self.assertEqual(self.left.to_counts("Z", 39.763), -256) # the rest Z
+ self.assertEqual(self.right.to_counts("Z1", 39.107921235034354), 9029) # the Span-8 Z park
+ self.assertEqual(self.right.to_counts("D1", 1000.0), 24000) # a pump's full stroke
+ self.assertAlmostEqual(self.left.to_value("X", self.left.to_counts("X", 42.0)), 42.0, 3)
+
+ def test_the_bridges_meet_where_biomek_stopped(self) -> None:
+ """The left bridge's right edge meets the right bridge's left edge at left X + |right X| =
+ 250,807 counts. Biomek never commanded more than 250,678 in 20 days of logs."""
+ lg, rg = self.left.geometry, self.right.geometry
+ left_reach = -lg.bridge_to_head_x_offset - lg.mandrel1_x_offset + lg.bridge_x_span
+ right_reach = -rg.bridge_to_head_x_offset - rg.mandrel1_x_offset
+ lx, rx = self.left.conversion["X"], self.right.conversion["X"]
+ # Deck X of a pod at `c` counts is c / const - offset; the edges meet when
+ # (L - R) / 2560 = (-rx.offset + right_reach) - (-lx.offset + left_reach).
+ combined = ((-rx.offset + right_reach) - (-lx.offset + left_reach)) * lx.const
+ self.assertEqual(round(combined), 250807)
+ self.assertLess(250678, combined)
+
+ def test_each_pod_works_from_its_own_corner_of_a_position(self) -> None:
+ """Heights Biomek logged (Details, 2026-10-20), less the moving pod's corner: the same at every
+ position, as the labware there is the same. The Multichannel (Pod1) approaching four plates to
+ dispense, and the Span-8 (Pod2) pressing onto tips in four boxes. Against the other pod's
+ corner they spread by up to 0.01 cm."""
+ positions = self.config.deck_positions
+ mc = {"P6": 27.757, "P9": 27.750, "P12": 27.756, "P16": 27.760}
+ span8 = {"P14": 20.741, "P15": 20.744, "P21": 20.737, "P23": 20.727}
+ for pod, logged, height in ((1, mc, 11.788), (2, span8, 4.770)):
+ for name, z in logged.items():
+ with self.subTest(pod=pod, position=name):
+ self.assertAlmostEqual(z - positions[name].corner(pod)[2], height, delta=0.0011)
+ self.assertEqual(positions["P6"].framed, {1: "Position", 2: "Position"})
+ with self.assertRaises(ValueError):
+ positions["P6"].corner(3)
+
+ def test_unknown_axis_and_side(self) -> None:
+ with self.assertRaises(ValueError):
+ self.left.to_counts("Z1", 1.0)
+ config = generic_configuration()
+ del config.pods["right"]
+ with self.assertRaisesRegex(ValueError, "no pod declared on the right"):
+ config.pod("right")
+
+
+class KeepingTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.folder = tempfile.TemporaryDirectory()
+ self.addCleanup(self.folder.cleanup)
+ self.path = os.path.join(self.folder.name, "configuration.json")
+
+ def test_save_and_load_round_trip(self) -> None:
+ config = generic_configuration()
+ config.save(self.path)
+ self.assertEqual(DeviceConfiguration.load(self.path).to_dict(), config.to_dict())
+ with open(GENERIC_CONFIGURATION, encoding="utf-8") as fh:
+ self.assertEqual(json.load(fh), config.to_dict())
+
+ def test_a_file_changed_after_import_is_refused_at_load(self) -> None:
+ for change in (
+ lambda data: data["pods"]["left"]["conversion"]["X"].update(const=1.0), # instrument file
+ lambda data: data["modules"]["span8"][0].update(hysteresis=7), # Master Controller record
+ ):
+ config = generic_configuration()
+ data = config.to_dict()
+ change(data)
+ with open(self.path, "w", encoding="utf-8") as fh:
+ json.dump(data, fh)
+ with self.assertRaisesRegex(ValueError, "not the ones imported"):
+ DeviceConfiguration.load(self.path)
+
+ def test_anonymized_keeps_no_serial_numbers_and_no_measured_hysteresis(self) -> None:
+ config = generic_configuration()
+ config.generic = False
+ config.chassis_serial_number = "A" * 32
+ config.instrument_serial_number = "B" * 11
+ for pod in config.pods.values():
+ pod.module_serial_number = "C" * 32
+ config.modules["span8"][0]["hysteresis"] = 12
+ config.sources = {
+ name: {"path": "C:/somewhere", "kind": "file", "read_at": "2026-01-01", "fingerprint": f}
+ for name, f in config.fingerprints().items()
+ }
+ generic = config.anonymized()
+ text = json.dumps(generic.to_dict())
+ for serial in ("A" * 32, "B" * 11, "C" * 32):
+ self.assertNotIn(serial, text)
+ self.assertTrue(generic.generic)
+ self.assertEqual({a["hysteresis"] for axes in generic.modules.values() for a in axes}, {0})
+ self.assertEqual({k for s in generic.sources.values() for k in s}, {"fingerprint"})
+ self.assertEqual(generic.unrecorded_changes(), [])
+ self.assertEqual(generic.to_dict(), generic_configuration().to_dict())
+
+
+class DeclaredAgainstFoundTests(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self) -> None:
+ asyncio.get_running_loop().set_debug(False)
+
+ async def discover_with(self, configuration: DeviceConfiguration) -> BiomekI7Driver:
+ driver = generic_driver(configuration=sealed(configuration))
+ self.addAsyncCleanup(driver.stop)
+ await driver.discover()
+ return driver
+
+ async def test_the_generic_instrument_matches(self) -> None:
+ driver = generic_driver()
+ self.addAsyncCleanup(driver.stop)
+ with self.assertNoLogs(MASTER_LOGGER, level="WARNING"):
+ await driver.discover()
+ assert driver.left_x_arm and driver.left_x_arm.declared
+ self.assertEqual(driver.left_x_arm.declared.component, "MC_1")
+
+ async def test_pods_swapped_are_refused(self) -> None:
+ config = generic_configuration()
+ left, right = config.pods["left"], config.pods["right"]
+ config.pods = {
+ "left": dataclasses.replace(right, side="left"),
+ "right": dataclasses.replace(left, side="right"),
+ }
+ with self.assertRaisesRegex(ValueError, "span8 pod on the left"):
+ await self.discover_with(config)
+
+ async def test_a_pod_declared_but_not_found_is_only_logged(self) -> None:
+ config = generic_configuration()
+ del config.pods["right"]
+ with self.assertLogs(MASTER_LOGGER, level="WARNING") as logs:
+ driver = await self.discover_with(config)
+ self.assertIn("right pod: declared nothing, found span8", "\n".join(logs.output))
+ assert driver.right_x_arm is not None
+ self.assertIsNone(driver.right_x_arm.declared)
+
+ async def test_another_instruments_configuration_is_not_checked_on_given_boards(self) -> None:
+ # Refused on the instrument's own boards (`serial_numbers_tests.py`); simulated ones are not
+ # tied to an instrument.
+ config = generic_configuration()
+ config.chassis_serial_number = "0" * 32
+ driver = await self.discover_with(config)
+ self.assertEqual(driver.declared.chassis_serial_number, "0" * 32)
+
+ def test_a_declared_configuration_is_required(self) -> None:
+ with self.assertRaisesRegex(ValueError, "no declared configuration"):
+ BiomekI7Driver(boards=[])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py b/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py
new file mode 100644
index 00000000000..dfe7c096599
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py
@@ -0,0 +1,141 @@
+"""Biomek i7 error types, and the reply bytes that raise them."""
+
+from typing import Dict, List, Mapping, Optional, Tuple
+
+# ACE error codes, the byte after a reply's status. The Master Controller names more, but their
+# numbers are not guessed.
+ACE_ERROR_NAMES: Dict[int, str] = {
+ 0x0F: "interlock tripped",
+ 0x30: "motion device not configured",
+ 0x31: "motion device not enabled",
+ 0x32: "motion device not homed",
+ 0x38: "coordinated motion failed",
+ 0x3C: "motion error window exceeded",
+}
+
+# Device error codes: the drive's own reason, after the ACE error code of a failed move, and in an
+# EMCY message. Each one here was seen in a reply or an EMCY message.
+DEVICE_ERROR_NAMES: Dict[int, str] = {
+ 0x0100: "motion error window exceeded",
+ 0x0407: "interlock tripped",
+ 0x0416: "interlock active",
+ 0x0431: "servo home aborted",
+ 0x0437: "stepper glitch",
+}
+
+
+class FrameError(Exception):
+ """Bytes from a board that do not split into whole frames."""
+
+
+class AceError(Exception):
+ """A board refused a command or reported that it failed.
+
+ Attributes:
+ code: the ACE error code.
+ device_error: the drive's own error code, when the reply carries one.
+ request: a short description of the command that failed.
+ axis_errors: for a failed Move All, the errors the axes that failed reported.
+ """
+
+ def __init__(
+ self,
+ code: int,
+ device_error: Optional[int],
+ request: str,
+ device: Optional[int] = None,
+ index: Optional[int] = None,
+ ):
+ self.code = code
+ self.device_error = device_error
+ self.request = request
+ # The device and index the reply came from, when known: which axis failed.
+ self.device = device
+ self.index = index
+ self.axis_errors: List["AceError"] = []
+ self.reason = ACE_ERROR_NAMES.get(code, f"ACE error 0x{code:02X}")
+ name = ACE_ERROR_NAMES.get(code, f"ACE error 0x{code:02X}")
+ detail = ""
+ if device_error is not None:
+ device_name = DEVICE_ERROR_NAMES.get(device_error)
+ detail = f" (device error 0x{device_error:X}" + (f": {device_name})" if device_name else ")")
+ super().__init__(f"{request}: {name}{detail}")
+
+
+class InterlockTrippedError(AceError):
+ """The interlock tripped (light curtain broken, or tripped by the host), so the board stopped or
+ refused the move."""
+
+
+class NotConfiguredError(AceError):
+ """The axis has no motor table loaded: the board was powered up, or the drive lost its
+ parameters, since the last Configure."""
+
+
+class NotEnabledError(AceError):
+ """The axis is configured but disabled (Set State ENABLED has not been sent since)."""
+
+
+class NotHomedError(AceError):
+ """The axis has not been homed since the board started."""
+
+
+class MotionError(AceError):
+ """A move did not complete: the axis left its error window, or a coordinated move failed."""
+
+
+# The ACE error a board answers when the interlock is tripped.
+INTERLOCK_TRIPPED_CODE = 0x0F
+
+_ERROR_CLASSES = {
+ INTERLOCK_TRIPPED_CODE: InterlockTrippedError,
+ 0x30: NotConfiguredError,
+ 0x31: NotEnabledError,
+ 0x32: NotHomedError,
+ 0x38: MotionError,
+ 0x3C: MotionError,
+}
+
+
+def ace_error(
+ code: int,
+ device_error: Optional[int],
+ request: str,
+ device: Optional[int] = None,
+ index: Optional[int] = None,
+) -> AceError:
+ """Build the exception for an ACE error code."""
+ return _ERROR_CLASSES.get(code, AceError)(code, device_error, request, device, index)
+
+
+# The errors the Master Controller reports as one axis's motion failing (not enabled, homing failed, operational parameters exceeded, error window exceeded, framing
+# error, controller error; only those with a known number here).
+_MOTION_FAILED_CODES = {0x31, 0x3C}
+COORDINATED_MOTION_FAILED_CODE = 0x38
+
+
+def english(error: AceError, axis_names: Mapping[Tuple[int, int], str]) -> str:
+ """What the Master Controller replies for a command that failed with `error`, as its logs show
+ it, with each axis named by `axis_names` ((device, index) ->
+ name):
+
+ - not homed: "The instrument needs to be homed.";
+ - interlock tripped: "A light curtain violation has occurred.";
+ - a coordinated move failed: "The motion failed: ." for each axis that reported;
+ - an axis's own motion error: the same, for that axis;
+ - anything else: " failed: ".
+ """
+
+ def motion_failed(e: AceError) -> str:
+ name = axis_names.get((e.device, e.index)) if e.device is not None else None # type: ignore[arg-type]
+ return f"The {name or e.request} motion failed: {e.reason}."
+
+ if isinstance(error, NotHomedError):
+ return "The instrument needs to be homed."
+ if isinstance(error, InterlockTrippedError):
+ return "A light curtain violation has occurred."
+ if error.code == COORDINATED_MOTION_FAILED_CODE and error.axis_errors:
+ return " ".join(motion_failed(e) for e in error.axis_errors)
+ if error.code in _MOTION_FAILED_CODES and error.device is not None:
+ return motion_failed(error)
+ return f"{error.request} failed: {error.reason}."
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/errors_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/errors_tests.py
new file mode 100644
index 00000000000..fa88302e947
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/errors_tests.py
@@ -0,0 +1,41 @@
+"""Board errors as the Master Controller words them in its replies, as its logs show them."""
+
+import unittest
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import ace_error, english
+
+NAMES = {(0x11, 1): "left X", (0x11, 3): "left Z"}
+
+
+class EnglishTests(unittest.TestCase):
+ def test_not_homed_and_interlock(self) -> None:
+ self.assertEqual(
+ english(ace_error(0x32, None, "Set X Move Parameters"), NAMES),
+ "The instrument needs to be homed.",
+ )
+ self.assertEqual(
+ english(ace_error(0x0F, None, "Move All"), NAMES),
+ "A light curtain violation has occurred.",
+ )
+
+ def test_a_coordinated_move_names_each_axis_that_failed(self) -> None:
+ error = ace_error(0x38, None, "Move All", 0x10, 0)
+ error.axis_errors = [
+ ace_error(0x3C, 0x0100, "device 0x11 index 1", 0x11, 1),
+ ace_error(0x3C, None, "device 0x11 index 3", 0x11, 3),
+ ]
+ self.assertEqual(
+ english(error, NAMES),
+ "The left X motion failed: motion error window exceeded. "
+ "The left Z motion failed: motion error window exceeded.",
+ )
+
+ def test_an_axis_error_and_anything_else(self) -> None:
+ self.assertEqual(
+ english(ace_error(0x31, None, "Move", 0x11, 1), NAMES),
+ "The left X motion failed: motion device not enabled.",
+ )
+ self.assertEqual(
+ english(ace_error(0x0A, None, "Get Tip Status"), NAMES),
+ "Get Tip Status failed: ACE error 0x0A.",
+ )
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py
new file mode 100644
index 00000000000..55989602bfb
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py
@@ -0,0 +1,60 @@
+"""Faults the boards report unasked, as the Master Controller handles them, and the positions: a
+motor that fails on its own trips the interlock and every position is forgotten; after an interlock
+trip, re-arming reads every position again."""
+
+import asyncio
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver
+from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest
+
+
+class FaultTests(PodMoveTest):
+ async def settle(self) -> None:
+ """Let the boards' read loops and the driver's background writes run."""
+ for _ in range(5):
+ await asyncio.sleep(0.02)
+
+ def unasked(self, driver: BiomekI7Driver, module: str, message: bytes) -> None:
+ self.usb(driver, module)._queue(message)
+
+ async def test_a_motor_failing_on_its_own_trips_the_interlock(self) -> None:
+ driver = await self.homed()
+ pod = self.pod(driver, "left")
+ await pod.move_axes({"X": 100000})
+ x = pod.axis("X")
+ self.mark(driver)
+ with self.assertLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "ERROR") as logs:
+ # A Move All's NOTICE for X with a following error, sequence 0: nobody asked.
+ self.unasked(driver, "multichannel", bytes([x.device, x.index, 0, 0, 0x50, 0xFE, 0x3C]))
+ await self.settle()
+ self.assertIn("The left X motor failed", "\n".join(logs.output))
+ self.assertEqual(
+ [n for n, _ in self.sent(driver, "chassis")], ["Trip Interlock", "Set Status Display"]
+ )
+ self.assertEqual(self.sent(driver, "chassis")[1][1], p.set_status_display("error").params)
+ self.assertIsNone(pod.cpositions["X"][0])
+ self.assertTrue(driver.interlock_tripped.is_set())
+
+ async def test_an_interlock_trip_forgets_positions_and_shows_error(self) -> None:
+ driver = await self.homed()
+ pod = self.pod(driver, "right")
+ await pod.move_axes({"Z1": -10000})
+ self.mark(driver)
+ with self.assertLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "ERROR"):
+ self.unasked(driver, "chassis", bytes([p.Device.INTERLOCK, 1, 0, 0, 0x10, 0x03, 0x00, 0x01]))
+ await self.settle()
+ self.assertEqual(
+ self.sent(driver, "chassis"), [("Set Status Display", p.set_status_display("error").params)]
+ )
+ self.assertTrue(all(c[0] is None for c in pod.cpositions.values() if c is not None))
+ # Re-arming reads every position again, as the Master Controller's resume does.
+ await driver.arm_interlock()
+ self.assertFalse(driver.interlock_tripped.is_set())
+ self.assertIsNotNone(pod.cpositions["Z1"][0])
+
+
+if __name__ == "__main__":
+ import unittest
+
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py
new file mode 100644
index 00000000000..fc83f97406e
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py
@@ -0,0 +1 @@
+"""What a Biomek i7 is fitted with: the chassis, and a pod per side (`pod.py`, STAR's X-arm)."""
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py
new file mode 100644
index 00000000000..0217e61071b
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py
@@ -0,0 +1,127 @@
+"""The chassis module: interlock, status display, deck I/O and the instrument's own sensors (the door
+is its own feature, `door.py`, read through the chassis)."""
+
+from typing import Dict, List, Optional
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ModuleConfiguration
+from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door
+from pylabrobot.beckman_coulter.biomek_i7.driver.module import (
+ read_analog_inputs,
+ read_module,
+)
+
+
+class Chassis:
+ """The chassis's ACE module. Reached as `driver.chassis`."""
+
+ def __init__(self, board: AceBoard):
+ self.board = board
+ self.configuration: Optional[ModuleConfiguration] = None
+ self.front_cover = Door(self)
+
+ async def discover(self) -> ModuleConfiguration:
+ """Read what the chassis says about itself. Moves nothing."""
+ self.configuration = await read_module(self.board)
+ return self.configuration
+
+ def _require_configuration(self) -> ModuleConfiguration:
+ if self.configuration is None:
+ raise RuntimeError("the chassis has not been read; call `discover()` or `setup()` first")
+ return self.configuration
+
+ async def request_analog_inputs(self) -> Dict[str, float]:
+ """Every analog input (supply voltages, temperature...) by name, in its units."""
+ return await read_analog_inputs(self.board, self._require_configuration())
+
+ async def request_digital_inputs(self) -> Dict[str, int]:
+ config = self._require_configuration()
+ replies = await self.board.send_many(
+ [p.read_input_output(p.Device.DIGITAL_INPUT, i) for i in config.digital_inputs]
+ )
+ return {config.digital_inputs[i]: r.payload[0] for i, r in zip(config.digital_inputs, replies)}
+
+ async def request_digital_outputs(self) -> Dict[str, int]:
+ config = self._require_configuration()
+ replies = await self.board.send_many(
+ [p.read_input_output(p.Device.DIGITAL_OUTPUT, i) for i in config.digital_outputs]
+ )
+ return {
+ config.digital_outputs[i]: r.payload[0] for i, r in zip(config.digital_outputs, replies)
+ }
+
+ async def request_legacy_alp_devices(self) -> List[bytes]:
+ """The legacy ALP devices the chassis lists, as the raw entries it answers."""
+ payload = (await self.board.send(p.list_legacy_alp_devices())).payload
+ return [payload[i : i + 2] for i in range(0, len(payload), 2)]
+
+ # -- interlock -------------------------------------------------------------
+ # The interlock cuts the arms' drive power when the light curtain is broken or the host trips it
+ # (the door does not: see `door.py`); nothing moves while it is tripped. It can be read, tripped and re-armed; there is
+ # deliberately no way here to bypass it.
+
+ async def request_interlock_state(self) -> p.InterlockState:
+ """`armed` (the drives may have power) or `tripped`. Moves nothing.
+
+ Biomek's logs never show the Master Controller sending Get Interlock Status. The request only
+ reads the state; it changes nothing.
+ """
+ return p.parse_interlock_status((await self.board.send(p.get_interlock_status())).payload)
+
+ async def prepare_interlock(self) -> None:
+ """Trip the interlock, ask to be told when it trips, and show READY, as before the motor tables
+ are loaded after a power-up."""
+ await self._unchecked_fw_trip_interlock()
+ await self._unchecked_fw_notify_on_interlock_trip()
+ await self._unchecked_fw_set_status_display("ready")
+
+ async def _io_box_write_after_configure(self) -> None:
+ """Send the legacy deck digital I/O box its WRITE 01, a cancel of what that box was doing:
+ Biomek's logs show it after every Stop Module Execution (the Master Controller stopping the
+ box), which in a cold start falls after the motor tables are loaded. Kept where the recorded
+ start sends it, so the start stays byte for byte; it has nothing to do with the light curtain."""
+ await self._unchecked_fw_send_digital_io_box(b"\x02\x01")
+
+ async def trip_interlock(self, error: bool = False) -> None:
+ """Cut the arms' drive power and show READY: how the Master Controller leaves the instrument
+ at rest (it does so at every start; the drive supply reads off in over 90% of its polls).
+ With `error`, show ERROR, as it does after a failed move."""
+ await self._unchecked_fw_trip_interlock()
+ await self._unchecked_fw_set_status_display("error" if error else "ready")
+
+ async def arm_interlock(self) -> None:
+ """Re-arm the interlock and show RUNNING. The light curtain must be clear.
+
+ Raises:
+ RuntimeError: if the interlock does not report ARMED.
+ """
+ state = await self._unchecked_fw_rearm_interlock()
+ if state[:1] != b"\x00":
+ raise RuntimeError(
+ f"the interlock did not arm (state {state.hex()}); is the light curtain clear?"
+ )
+ await self._unchecked_fw_set_status_display("running")
+
+ # -- firmware commands -----------------------------------------------------
+ # The chassis's writes, one request each, as the Master Controller sends them. No checks and no
+ # bookkeeping: the public methods above decide when each is sent.
+
+ async def _unchecked_fw_trip_interlock(self) -> None:
+ await self.board.send(p.trip_interlock())
+
+ async def _unchecked_fw_rearm_interlock(self) -> bytes:
+ """Re-Arm Interlock. Returns what it answers: `00` when armed."""
+ return (await self.board.send(p.rearm_interlock())).payload
+
+ async def _unchecked_fw_notify_on_interlock_trip(self) -> None:
+ await self.board.send(p.notify_on_interlock_trip())
+
+ async def _unchecked_fw_set_status_display(self, state: p.StatusDisplayState) -> None:
+ await self.board.send(p.set_status_display(state))
+
+ async def _unchecked_fw_send_digital_io_box(self, data: bytes) -> None:
+ await self.board.send(p.send_digital_io_box(data))
+
+ async def _unchecked_fw_notify_on_input_change(self, index: int, notify: bool) -> None:
+ await self.board.send(p.notify_on_change(p.Device.DIGITAL_INPUT, index, notify))
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/door.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/door.py
new file mode 100644
index 00000000000..695fc5cbcaa
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/door.py
@@ -0,0 +1,58 @@
+"""The instrument's door: STAR's `FrontCover`, and reached by its name, `driver.front_cover` /
+`biomek.front_cover`.
+
+The door sensor is the chassis's digital input "Door Sensor": 1 closed, 0 open. The door only
+reports: opening it does not trip the interlock, and Biomek arms the interlock with it open
+(Biomek's logs, July to October 2026). The interlock (`chassis`) answers to the light curtain and
+to the host. STAR's `enable_control` / `disable_control` have no counterpart here: the door has no
+interlock to turn off.
+"""
+
+from typing import TYPE_CHECKING, Callable, Literal
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+
+if TYPE_CHECKING:
+ from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis
+
+DoorState = Literal["open", "closed"]
+DOOR_SENSOR_INPUT = "Door Sensor"
+DOOR_CLOSED = 1
+
+
+class Door:
+ """The door, read through the chassis's door sensor."""
+
+ def __init__(self, chassis: "Chassis"):
+ self._chassis = chassis
+
+ def _input(self) -> int:
+ config = self._chassis._require_configuration()
+ for index, name in config.digital_inputs.items():
+ if name == DOOR_SENSOR_INPUT:
+ return index
+ raise RuntimeError(f"the chassis has no digital input named {DOOR_SENSOR_INPUT!r}")
+
+ async def request_state(self) -> DoorState:
+ """Whether the door is open or closed (STAR's `FrontCover.request_state`). Moves nothing."""
+ board = self._chassis.board
+ reply = await board.send(p.read_input_output(p.Device.DIGITAL_INPUT, self._input()))
+ return "closed" if reply.payload[0] == DOOR_CLOSED else "open"
+
+ def subscribe(self, callback: Callable[[DoorState], None]) -> Callable[[], None]:
+ """Call `callback` whenever the door opens or closes. Returns an unsubscribe.
+
+ The chassis reports changes only once asked to (Notify On Digital Input Change, which the
+ Master Controller sends at every start and `notify_changes` sends)."""
+ index = self._input()
+
+ def on_message(reply: p.Reply) -> None:
+ if (reply.device, reply.opcode) == p.DIGITAL_INPUT_VALUE and reply.index == index:
+ callback("closed" if reply.payload[:1] == bytes([DOOR_CLOSED]) else "open")
+
+ return self._chassis.board.subscribe(on_message)
+
+ async def notify_changes(self, notify: bool = True) -> None:
+ """Ask the chassis to report the door opening and closing (or, False, to stop). Moves
+ nothing."""
+ await self._chassis._unchecked_fw_notify_on_input_change(self._input(), notify)
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py
new file mode 100644
index 00000000000..73c8e9961c5
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py
@@ -0,0 +1,1085 @@
+"""One pod: an arm on the shared X rail, its ACE module, and the axes that module drives."""
+
+import logging
+import math
+from dataclasses import dataclass, field
+from typing import (
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Literal,
+ Mapping,
+ Optional,
+ Sequence,
+ Set,
+ Tuple,
+ cast,
+)
+
+from pylabrobot.beckman_coulter.biomek_i7 import units
+from pylabrobot.beckman_coulter.biomek_i7.driver import motion
+from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc
+from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import (
+ ModuleConfiguration,
+ PodConfiguration,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english
+from pylabrobot.beckman_coulter.biomek_i7.driver.module import (
+ read_analog_inputs,
+ read_module,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, AxisMove, MotorTables
+from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import (
+ ENABLE_ORDER,
+ ENABLE_PREFIX,
+ HOME_RECIPES,
+ Homer,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail
+
+logger = logging.getLogger(__name__)
+
+# How Biomek numbers its pods. Pod1 is the left pod and Pod2 the right on the instrument this
+# driver was written against; whether that holds on every build is not established.
+POD_NUMBERS = {"left": 1, "right": 2}
+COMPONENT_PREFIXES = {"multichannel": "MC", "span8": "SPAN8"}
+# The axes that change what a pod takes up along the X rail.
+RAIL_AXES = ("X", "GR", "GG")
+# The gripper's axes; a move of these, or of the channels' Y or Z, is checked against the pod's own
+# parts (`pod_collision`).
+OWN_COLLISION_AXES = {"GY", "GZ", "GR", "GG"}
+GRIPPER_HEIGHT_STEP = 0.1 # cm: how finely the gripper's travel height is searched
+
+# Get Homed State answers. 0x01 was read from every axis at a cold start, 0x00 from every axis of
+# both pods after Biomek's Home All (H1, 2026-10-24).
+HOMED_STATES = {0x00: "homed", 0x01: "not_homed"}
+
+# The timeouts the Master Controller gives the boards: a single axis's move, and a Move All.
+MOVE_TIMEOUT_MS = 30000
+MOVE_ALL_TIMEOUT_MS = 5000
+
+# Biomek's "Safe Height" (`GlobalMinSafeHeight`) at or below this is unset (it stores -100000).
+UNSET_SAFE_HEIGHT = -1000.0
+
+# The arm board's analog input carrying the interlocked motor supply ("+36V Interlock").
+DRIVE_SUPPLY_INPUT = "+36V Interlock"
+
+# Set State ENABLED on a CiA 402 drive resets a fault, then steps the drive through shutdown, switch
+# on and enable operation, waiting up to 3 s for each. Whether a board enables
+# a batch one drive at a time is not known, so a batch is given that per axis; it is a bound for
+# a drive that does not come up, not how long enabling takes.
+ENABLE_SECONDS_PER_AXIS = 9.0
+
+
+@dataclass(frozen=True)
+class MoveResult:
+ """What a coordinated move did: the motions it sent (empty when every axis was already there),
+ and each axis's report that was not a plain finish. A sensor stop says where
+ (`MotionComplete.position`)."""
+
+ motions: List[motion.Motion] = field(default_factory=list)
+ completions: Dict[str, p.MotionComplete] = field(default_factory=dict)
+
+ def stopped_at(self, axis: str) -> Optional[int]:
+ """Where a sensor stopped `axis`, in counts; None if none did."""
+ complete = self.completions.get(axis)
+ return complete.position if complete is not None else None
+
+
+# How long this driver waits for a board to answer a Home, in seconds. The longest homing seen
+# took 9 s; the boards' own homing timeouts (Configure "Homing Timeout") are up to 60 s.
+HOME_REPLY_TIMEOUT = 65.0
+
+
+class Pod:
+ """One pod. Reached as `driver.left_x_arm` / `driver.right_x_arm`: it fills the slot of STAR's
+ `XArm`, though more of the instrument hangs on it. One board drives its X, Y and Z, its head
+ or channels and its gripper, through one position record.
+
+ Holds what every pod has: one board and its axes, moved together (`move_axes`, the Master
+ Controller's `AM`), the position record the Master Controller keeps, homing, and the pod's pose
+ on the shared X rail. `module_type` is what the board reports itself to be: `multichannel` (a
+ 96-channel head) or `span8` (eight independent channels).
+ """
+
+ def __init__(
+ self,
+ board: AceBoard,
+ side: Literal["left", "right"],
+ module_type: str,
+ motor_tables: MotorTables,
+ declared: Optional[PodConfiguration] = None,
+ ):
+ self.board = board
+ self.side = side
+ self.module_type = module_type
+ self.axes: List[Axis] = motor_tables.axes(module_type)
+ self.configuration: Optional[ModuleConfiguration] = None
+ # What the instrument's declared configuration says about this pod: its conversions, travel
+ # limits and geometry. None when nothing is declared for this side.
+ self.declared = declared
+ # The shared X rail, set by the driver once both pods are found. Every move that changes what
+ # the pod takes up along it (X, the gripper's GR or GG) goes through it.
+ self.rail: Optional[XRail] = None
+ # What the gripper holds, as the rail counts it; the pod cannot sense it.
+ self._held_labware: Optional[g.HeldLabware] = None
+ # Where this driver last put each axis, as the Master Controller keeps it (`cpositions`):
+ # (position, adjusted); position None until read. Starts as after homing.
+ self._cpositions: Dict[str, motion.CPos] = {a.name: (None, a.home_position) for a in self.axes}
+ # The pumps' state, kept with the positions as the Master Controller keeps it in the Span-8's
+ # state record, because every pump move carries it. Each syringe
+ # pump's valve as last set (None until then), and the cutoff velocity (`CV`), counts/s,
+ # clamped to each pump's range when used.
+ self._valves: Dict[str, Optional[p.Valve]] = {a.name: None for a in self.axes if a.is_pump}
+ self._cutoff_velocity = 0
+ # The height the channels rise to before traveling over the deck, mm of the channels' bottom
+ # above the deck: STAR's `default_minimum_traverse_height`. Seeded from Biomek's "Safe Height"
+ # (`GlobalMinSafeHeight`) when it is set; None, as on an instrument where it is not (-100000),
+ # means the top of travel less the park margin, which is what Biomek does with Safe Height set
+ # to the top.
+ self.default_minimum_traverse_height: Optional[float] = None
+ if declared is not None:
+ safe = declared.settings.get("GlobalMinSafeHeight")
+ if isinstance(safe, (int, float)) and safe > UNSET_SAFE_HEIGHT:
+ self.default_minimum_traverse_height = units.to_mm(float(safe))
+ # Who follows the position record (`add_position_listener`).
+ self._listeners: List[Callable[["Pod"], None]] = []
+
+ @property
+ def pod_number(self) -> int:
+ return POD_NUMBERS[self.side]
+
+ def __str__(self) -> str:
+ return f"{self.side} pod (Pod{self.pod_number}, {self.module_type})"
+
+ @property
+ def component(self) -> str:
+ """The name Biomek gives this pod's component in its logs (`host_command.component`):
+ `MC_1`, `SPAN8_2`. The driver's own log lines for host commands use it too, so a session can
+ be lined up with one of Biomek's."""
+ return f"{COMPONENT_PREFIXES[self.module_type]}_{self.pod_number}"
+
+ def axis(self, name: str) -> Axis:
+ for axis in self.axes:
+ if axis.name == name:
+ return axis
+ raise ValueError(f"{self} has no axis {name!r}; it has {[a.name for a in self.axes]}")
+
+ async def discover(self) -> ModuleConfiguration:
+ """Read what the pod's module says about itself. Moves nothing."""
+ self.configuration = await read_module(self.board)
+ return self.configuration
+
+ async def request_positions(self) -> Dict[str, int]:
+ """Every axis's current position, in counts, as the drives report it."""
+ replies = await self.board.send_many(
+ [p.get_current_position(axis.device, axis.index) for axis in self.axes]
+ )
+ return {axis.name: p.parse_s32(r.payload) for axis, r in zip(self.axes, replies)}
+
+ async def request_axis_states(self) -> Dict[str, p.AxisStateName]:
+ """Every axis's state (motors and pumps), sent together: `enabled` (it may move), `disabled`
+ (configured, not enabled), `not_configured` (as at power-up) or `fault`. Moves nothing.
+
+ Raises:
+ ValueError: for a state byte the firmware does not set.
+ """
+ replies = await self.board.send_many([p.get_state(a.device, a.index) for a in self.axes])
+ return {
+ a.name: cast(p.AxisStateName, p.parse_axis_state(r.payload).name.lower())
+ for a, r in zip(self.axes, replies)
+ }
+
+ async def request_drive_supply(self) -> float:
+ """The pod's interlocked motor supply, in volts: about 36 with the interlock armed, about 0.1
+ tripped. Moves nothing.
+
+ Raises:
+ RuntimeError: if the pod has no input named for it.
+ """
+ if self.configuration is None:
+ raise RuntimeError(f"{self} has not been read; call `discover()` or `setup()` first")
+ for index, name in self.configuration.analog_inputs.items():
+ if name.startswith(DRIVE_SUPPLY_INPUT):
+ reply = await self.board.send(p.read_input_output(p.Device.ANALOG_INPUT, index))
+ return p.parse_float(reply.payload)
+ raise RuntimeError(f"{self} has no {DRIVE_SUPPLY_INPUT!r} analog input")
+
+ async def request_homed_state(self, axis_name: str) -> str:
+ """Whether an axis (a motor or a pump) has been homed: `homed`, `not_homed`, or the raw code
+ of a state not yet seen."""
+ axis = self.axis(axis_name)
+ code = (await self.board.send(p.get_homed_state(axis.device, axis.index))).payload[0]
+ return HOMED_STATES.get(code, f"0x{code:02X}")
+
+ async def request_accuframe_offsets(self) -> Tuple[float, float, float]:
+ """The X, Y and Z offsets the pod's AccuFrame board holds."""
+ return p.parse_accuframe_offsets((await self.board.send(p.get_accuframe_offsets())).payload)
+
+ async def request_analog_inputs(self) -> Dict[str, float]:
+ if self.configuration is None:
+ raise RuntimeError(f"{self} has not been read; call `discover()` or `setup()` first")
+ return await read_analog_inputs(self.board, self.configuration)
+
+ # -- configuration and homing ------------------------------------------------
+ # These write to the board and move the arm. Nothing in this driver calls them on its own.
+
+ async def configure(self) -> None:
+ """Load every axis's motor table into the board, then Stop Module Execution, as after a
+ power-up. The tables come from the motor recording; the board cannot be asked for them.
+
+ Configuring an axis that is configured is accepted, and leaves it disabled and not homed, so
+ this un-homes the pod."""
+ logger.info("%s configure (%d axes)", self.component, len(self.axes))
+ self._set_home_positions(a.name for a in self.axes)
+ for axis in self.axes:
+ await self._unchecked_fw_configure(axis)
+ await self._unchecked_fw_stop_module_execution()
+
+ async def enable_axes(self) -> Dict[str, int]:
+ """Stop motion and enable every axis, as after the interlock is armed (its drive power was
+ off), and read where each is, as the Master Controller resumes: the positions cleared, then
+ each axis enabled and read. Returns every axis's position."""
+ axes = [self.axis(name) for name in ENABLE_ORDER[self.module_type]]
+ self._forget_positions()
+ await self._unchecked_fw_enable(ENABLE_PREFIX[self.module_type])
+ await self._unchecked_fw_stop_motion()
+ await self._unchecked_fw_enable(ENABLE_ORDER[self.module_type])
+ replies = await self.board.send_many([p.get_current_position(a.device, a.index) for a in axes])
+ positions = {a.name: p.parse_s32(r.payload) for a, r in zip(axes, replies)}
+ # As the Master Controller does, each read is the axis's position.
+ for axis in axes:
+ self._cpositions[axis.name] = motion.update_cpos(
+ self._cpositions[axis.name], positions[axis.name], axis.hysteresis
+ )
+ self._positions_changed()
+ return positions
+
+ async def home(self, force: bool = False) -> None:
+ """Home every axis but the plunger (or syringe pumps), in the Master Controller's `HM` order.
+
+ Axes not homed are homed. Axes already homed are moved to where a Home would leave them, or,
+ with `force`, moved to their approach positions and homed again as `HM` does. Each ends where
+ Biomek leaves it."""
+ logger.info("%s HM%s", self.component, "" if force else " (homed axes kept)")
+ try:
+ await Homer(self, force=force).run(HOME_RECIPES[self.module_type])
+ finally:
+ self._set_home_positions(Homer.axes(HOME_RECIPES[self.module_type]))
+
+ # -- coordinated moves -------------------------------------------------------
+ # The Master Controller's `AM`, with its position bookkeeping: see `motion.py`.
+
+ @property
+ def cpositions(self) -> Dict[str, motion.CPos]:
+ """Each axis's (position, adjusted), as this driver keeps them; position None until read."""
+ return dict(self._cpositions)
+
+ def _set_home_positions(self, names: Iterable[str]) -> None:
+ """After homing: position unknown, adjusted at the axis's home."""
+ for name in names:
+ self._cpositions[name] = (None, self.axis(name).home_position)
+ self._positions_changed()
+
+ def _forget_positions(
+ self,
+ names: Optional[Iterable[str]] = None,
+ adjusted: Optional[Mapping[str, motion.CPos]] = None,
+ ) -> None:
+ """Mark positions unknown, so the next move reads them first; adjusted
+ positions stay, or are taken from `adjusted`."""
+ for name in list(self._cpositions) if names is None else names:
+ self._cpositions[name] = (None, (adjusted or self._cpositions)[name][1])
+ self._positions_changed()
+
+ async def _read_unknown_positions(self, pumps: bool = False) -> None:
+ """As the Master Controller does before every move: if any axis's position is
+ unknown, Stop Motion Service, then enable and read each such axis. Syringe pumps are included
+ only when the move uses them (`pumps`)."""
+ unknown = [
+ a for a in self.axes if (pumps or not a.is_pump) and self._cpositions[a.name][0] is None
+ ]
+ if not unknown:
+ return
+ await self._unchecked_fw_stop_motion()
+ await self._unchecked_fw_enable([a.name for a in unknown])
+ replies = await self.board.send_many(
+ [p.get_current_position(a.device, a.index) for a in unknown]
+ )
+ for axis, reply in zip(unknown, replies):
+ position = p.parse_s32(reply.payload)
+ self._cpositions[axis.name] = motion.update_cpos(
+ self._cpositions[axis.name], position, axis.hysteresis
+ )
+ self._positions_changed()
+
+ async def request_x_position(self) -> int:
+ """Where the pod's X is, in counts, as its drive reports it. Moves nothing."""
+ x = self.axis("X")
+ return p.parse_s32((await self.board.send(p.get_current_position(x.device, x.index))).payload)
+
+ # -- the pod against itself ----------------------------------------------------
+
+ def _own_state(
+ self, positions: Optional[Mapping[str, motion.CPos]] = None
+ ) -> Optional[Tuple[float, pc.GripperState, pc.PipettorState]]:
+ """The pose the pod's own collision check takes (`pod_collision`), in Biomek's units, from
+ `positions` (the position record by default); None while any of its axes is unknown."""
+ d = self.declared
+ if d is None or not d.gripper_model:
+ return None
+ positions = self._cpositions if positions is None else positions
+ channels = self.channel_z_axes
+ ys = [f"Y{i}" for i in range(1, 9)] if self.module_type == "span8" else ["Y"]
+ names = ["X", "GY", "GZ", "GR", "GG", *ys, *channels]
+ counts = {n: positions[n][0] for n in names}
+ if any(c is None for c in counts.values()):
+ return None
+ v = {n: d.to_value("Y" if n in ys else n, c) for n, c in counts.items()} # type: ignore[arg-type]
+ if self.module_type == "span8":
+ # Each probe's Y counts from its own narrowest place (`probe_y`), not probe 1's.
+ v.update({n: d.probe_y(i, counts[n]) for i, n in enumerate(ys, 1)}) # type: ignore[arg-type]
+ lengths: Dict[str, float] = {} # no channel carries a tip
+ gripper = pc.GripperState(v["GY"], v["GZ"], v["GR"], v["GG"], self._held_labware)
+ pipettor = pc.PipettorState(
+ tuple(v[n] for n in ys),
+ tuple(v[z] for z in channels),
+ tuple(lengths.get(z, 0.0) for z in channels),
+ )
+ return v["X"], gripper, pipettor
+
+ def _check_own_collision(
+ self,
+ start: Mapping[str, motion.CPos],
+ end: Mapping[str, motion.CPos],
+ moving: Set[str],
+ ) -> None:
+ """Refuse a move whose path brings the gripper (or what it holds) into the pipettor.
+
+ Raises:
+ PodCollisionError: naming the parts that would meet; nothing has been sent.
+ """
+ if not moving & OWN_COLLISION_AXES and not any(a[:1] in "YZ" for a in moving):
+ return
+ a, b = self._own_state(start), self._own_state(end)
+ if a is None or b is None or self.declared is None:
+ return
+ found = pc.swept_collisions(self.declared, (a[0], b[0]), (a[1], b[1]), (a[2], b[2]))
+ if found:
+ parts = ", ".join(f"the {x} and {y}" for x, y in found[:3])
+ raise pc.PodCollisionError(f"{self}: the move would bring together {parts}")
+
+ def _gripper_traverse_height(self, gr: float) -> float:
+ """The GZ (cm) the gripper travels at to turn from where it is to GR `gr` (degrees): its
+ ceiling (`_traverse_ceilings`), or as far below it as keeps it (and what it holds) clear of the
+ pod's own pipettor at its traverse heights on the way, in steps of `GRIPPER_HEIGHT_STEP`.
+
+ Raises:
+ PodCollisionError: if no height down to the grip's travel limit is clear.
+ """
+ d = self._require_declared()
+ state = self._own_state()
+ ceiling = self._traverse_ceilings()["GZ"]
+ if state is None:
+ return ceiling
+ x, gripper, pipettor = state
+ heights = self._traverse_heights()
+ raised = pc.PipettorState(
+ pipettor.ys,
+ tuple(max(z, heights[n]) for z, n in zip(pipettor.zs, self.channel_z_axes)),
+ pipettor.tips,
+ )
+ low = d.limits["GZ"][0]
+ gz = ceiling
+ while gz >= low:
+ a = pc.GripperState(gripper.gy, gz, gripper.gr, gripper.gg, gripper.held)
+ b = pc.GripperState(gripper.gy, gz, gr, gripper.gg, gripper.held)
+ if not pc.swept_collisions(d, (x, x), (a, b), (raised, raised)):
+ return gz
+ gz -= GRIPPER_HEIGHT_STEP
+ raise pc.PodCollisionError(f"{self}: no gripper height clears the pod's own parts at GR {gr}")
+
+ async def _make_room_for_gripper(self, targets: Mapping[str, int]) -> None:
+ """Before the gripper travels to `targets` (counts: X, GY, GR): on a Span-8 whose probes
+ would be in its way there, narrow them to the smallest span and move them to the end of their
+ Y travel away from the gripper (as Biomek's path search does when it minimises the pod's Y
+ span). Nothing on a 96-head pod, or with the probes already clear.
+
+ Raises:
+ PodCollisionError: if the probes cannot be moved clear.
+ """
+ if self.module_type != "span8":
+ return
+ d = self._require_declared()
+ await self._read_unknown_positions()
+ state = self._own_state()
+ if state is None:
+ return
+ x, gripper, pipettor = state
+ gy = d.to_value("GY", targets.get("GY", self._cpositions["GY"][1]))
+ gr = d.to_value("GR", targets.get("GR", self._cpositions["GR"][1]))
+ gz = self._gripper_traverse_height(gr) if gr != gripper.gr else gripper.gz
+ end = pc.GripperState(gy, gz, gr, gripper.gg, gripper.held)
+ if not pc.collisions(d, x, end, pipettor):
+ return
+ low, high = d.limits["Y"]
+ span = d.limits["Span"][0]
+ y = low if gy >= (low + high) / 2 else high - span
+ ys = tuple(y + i * span / (len(pipettor.ys) - 1) for i in range(len(pipettor.ys)))
+ if pc.collisions(d, x, end, pc.PipettorState(ys, pipettor.zs, pipettor.tips)):
+ raise pc.PodCollisionError(f"{self}: the probes cannot be moved clear of the gripper")
+ await self._lift_channels()
+ await self.move_axes({"Y": d.to_counts("Y", y), "S": d.to_counts("S", span)})
+
+ async def _travel_gripper(
+ self,
+ targets: Mapping[str, int],
+ speed: int = 1000,
+ minimum_traverse_height: Optional[float] = None,
+ ) -> MoveResult:
+ """Take the gripper to `targets` (counts: X, GY, GR) clear of the deck and of the pod's own
+ pipettor: the channels raised (`_move_over`), the probes moved out of its way
+ (`_make_room_for_gripper`), the gripper at the highest height that clears the pod's own parts
+ for the turn (`_gripper_traverse_height`), lowered to it first if it is above."""
+ d = self._require_declared()
+ await self._read_unknown_positions()
+ await self._make_room_for_gripper(targets)
+ gr = d.to_value("GR", targets.get("GR", self._cpositions["GR"][1]))
+ gz = self._gripper_traverse_height(gr)
+ if d.to_counts("GZ", gz) < self._cpositions["GZ"][1]:
+ await self.move_axes({"GZ": d.to_counts("GZ", gz)}, speed)
+ return await self._move_over(
+ targets, speed, minimum_traverse_height=minimum_traverse_height, gripper_height=gz
+ )
+
+ # -- the shared X rail ---------------------------------------------------------
+
+ def _rail_pose(self, x: int, gr: Optional[int], gg: Optional[int]) -> PodPose:
+ """A pose in counts as the rail takes it: deck X, and the gripper in degrees and cm."""
+ d = self._require_declared()
+ gripper = None
+ if gr is not None and gg is not None:
+ gripper = g.GripperPose(d.to_value("GR", gr), d.to_value("GG", gg), self._held_labware)
+ return PodPose(d.to_value("X", x), gripper)
+
+ def _require_declared(self) -> PodConfiguration:
+ if self.declared is None:
+ raise RuntimeError(f"{self} has no declared configuration")
+ return self.declared
+
+ def add_position_listener(self, listener: Callable[["Pod"], None]) -> Callable[[], None]:
+ """Call `listener(pod)` whenever the position record changes: after a move, a read, homing,
+ or a position becoming unknown. Returns what removes it. For what follows the pod, such as its
+ model in a resource tree; a listener that raises is logged and kept."""
+ self._listeners.append(listener)
+ return lambda: self._listeners.remove(listener)
+
+ def _positions_changed(self) -> None:
+ self._tell_rail()
+ for listener in list(self._listeners):
+ try:
+ listener(self)
+ except Exception:
+ logger.exception("%s: position listener %r failed", self, listener)
+
+ def _tell_rail(self) -> None:
+ """Give the rail this pod's pose from the position record (unknown parts as unknown)."""
+ if self.rail is None or self.declared is None:
+ return
+ x = self._cpositions["X"][0]
+ pose = None
+ if x is not None:
+ pose = self._rail_pose(x, self._cpositions["GR"][0], self._cpositions["GG"][0])
+ self.rail.update(self.side, pose)
+
+ async def request_rail_pose(self) -> PodPose:
+ """Where the pod is along the rail, as its drives report X, GR and GG. Moves nothing."""
+ axes = [self.axis(n) for n in ("X", "GR", "GG")]
+ replies = await self.board.send_many([p.get_current_position(a.device, a.index) for a in axes])
+ x, gr, gg = (p.parse_s32(r.payload) for r in replies)
+ return self._rail_pose(x, gr, gg)
+
+ async def move_axes(
+ self,
+ targets: Mapping[str, int],
+ speed: int = 1000,
+ forces: Optional[Mapping[str, float]] = None,
+ sensors: Optional[Mapping[str, Tuple[int, int]]] = None,
+ ) -> MoveResult:
+ """Move several axes together so they arrive at once: Biomek's `AM` (with `SF` force limits and
+ sensor stops). The slowest axis moves at its limits x
+ speed / 1000, the others scaled to match; axes already at their target stay put.
+
+ Targets are in counts. On the Span-8 Z channels they are adjusted positions (the channel's
+ hysteresis is added to downward moves, as Biomek does). Syringe pumps move through the valve
+ each was last set to, at the cutoff velocity last set, as the Master Controller carries both.
+
+ A move of X, GR or GG is checked against the other pod first (`driver/x_rail.py`). One that
+ would run into it is refused, and nothing is sent. One crossing only the path of the other
+ pod's move in flight waits for that move to finish. Whether the pod may move now (interlock
+ armed) is the caller's to decide.
+
+ Args:
+ targets: target per axis name. On a Span-8, also `Y` (channel 1) and `S` (the span from
+ channel 1 to 8), as Biomek sends them: they set Y1-Y8 as the Master Controller does
+ (`motion.span_targets`), and cannot be given with Y1-Y8.
+ speed: 1..1000, Biomek's speed field.
+ forces: force limit per axis, in the Master Controller's units (its `SF`; sent x1000). The
+ axis stops where that force stalls it (a grip, a tip pressed on); its position is then
+ not known until read, which the next move does.
+ sensors: per axis, the (sensor, trigger) that stops it where the sensor fires (a Span-8 Z
+ sensing liquid). Where it stopped is in the result and becomes the axis's position, as
+ the Master Controller keeps it. Whether liquid not sensed or a clot is an
+ error is the caller's to decide (the Master Controller fails the `AM` for the first and
+ reports the second).
+
+ Returns:
+ The motions sent and how the axes ended.
+
+ Raises:
+ ValueError: for an unknown axis, a target outside an axis's limits, a force or sensor on an
+ axis without a target, or a speed outside 1..1000; nothing is sent.
+ RuntimeError: for a pump whose valve this driver has not set; nothing is sent.
+ NotHomedError: if an axis has not been homed; its pending moves are dropped.
+ RailCollisionError: if X, GR or GG would move into the other pod's range; nothing is sent.
+ PodCollisionError: if the gripper (or what it holds) would meet the pod's own pipettor on
+ the way (`pod_collision`); nothing is sent.
+ """
+ forces, sensors = dict(forces or {}), dict(sensors or {})
+ given, targets = dict(targets), dict(targets)
+ if self.module_type == "span8" and ("Y" in targets or "S" in targets):
+ channels = sorted(n for n in targets if n in {f"Y{i}" for i in range(1, 9)})
+ if channels:
+ raise ValueError(f"{self}: Y or S with {channels}; give one or the other")
+ y, span = targets.pop("Y", None), targets.pop("S", None)
+ targets.update(motion.span_targets(self._cpositions, y, span))
+ if not 1 <= speed <= 1000:
+ raise ValueError(f"speed {speed} is outside 1..1000")
+ for name, target in targets.items():
+ axis = self.axis(name)
+ axis.check_position(target)
+ if axis.is_pump and self._valves[name] is None:
+ raise RuntimeError(f"{self}: {name}'s valve has not been set")
+ stray = sorted({*forces, *sensors} - set(targets))
+ if stray:
+ raise ValueError(f"{self}: a force or sensor on {stray}, which have no target")
+ for name, force in forces.items():
+ if self.axis(name).is_pump or not 0 <= force <= p.MAX_FORCE:
+ raise ValueError(
+ f"{self}: force {force} on {name}: not a motor, or outside 0..{p.MAX_FORCE}"
+ )
+ uses_pumps = any(self.axis(n).is_pump for n in targets)
+ try:
+ await self._read_unknown_positions(pumps=uses_pumps)
+ motions, timeout_ms, after = motion.plan_move(
+ self.axes, self._cpositions, targets, speed, self._cutoff_velocity
+ )
+ logger.info(
+ "%s AM %s speed %d%s%s: %d axes move, Move All timeout %d ms",
+ self.component,
+ " ".join(f"{n}={t}" for n, t in given.items()),
+ speed,
+ "".join(f" SF {n} {f}" for n, f in forces.items()),
+ "".join(f" sensor {n} {s} {t}" for n, (s, t) in sensors.items()),
+ len(motions),
+ timeout_ms,
+ )
+ if not motions:
+ return MoveResult()
+ self._check_own_collision(self._cpositions, after, {m.axis for m in motions})
+ if self.rail is not None and any(m.axis in RAIL_AXES for m in motions):
+ start = self._rail_pose(*(self._cpositions[n][0] or 0 for n in RAIL_AXES))
+ end_counts = [after[n][0] or 0 for n in RAIL_AXES]
+ if "GG" in forces: # stops on what it grips, short of its target: count the wider end
+ end_counts[2] = max(end_counts[2], self._cpositions["GG"][0] or 0)
+ end = self._rail_pose(*end_counts)
+ async with self.rail.moving(self.side, start, end):
+ completions = await self._send_motions(motions, timeout_ms, forces, sensors)
+ else:
+ completions = await self._send_motions(motions, timeout_ms, forces, sensors)
+ except (RailCollisionError, pc.PodCollisionError):
+ raise # refused before anything was sent: every position is as it was
+ except BaseException as e:
+ # As the Master Controller after a failed command, and its reply, so a
+ # session's log reads as Biomek's: "#AM The left X motion failed: ...".
+ self._forget_positions()
+ if isinstance(e, AceError):
+ names = {(a.device, a.index): f"{self.side} {a.name}" for a in self.axes}
+ logger.error("%s #AM %s", self.component, english(e, names))
+ raise
+ before = self._cpositions
+ self._cpositions = after
+ # Force stopped these short of where they were sent: as the Master Controller does, their
+ # positions become unknown (adjusted as before), read before the next move.
+ if forces:
+ self._forget_positions(forces, before)
+ # A sensor stop reports where it stopped; the Master Controller takes that as the position.
+ for name, complete in completions.items():
+ if complete.position is not None and name not in forces:
+ axis = self.axis(name)
+ self._cpositions[name] = motion.update_cpos(
+ self._cpositions[name], complete.position, axis.hysteresis
+ )
+ self._positions_changed()
+ return MoveResult(list(motions), completions)
+
+ # -- travel over the deck (design.md I12) -------------------------------------------
+
+ @property
+ def channel_z_axes(self) -> List[str]:
+ """The axes whose height is the channels' bottom: `Z` on a Multichannel, `Z1`-`Z8` on a Span-8."""
+ return [
+ a.name for a in self.axes if a.name == "Z" or (a.name[0] == "Z" and a.name[1:].isdigit())
+ ]
+
+ def _traverse_heights(self) -> Dict[str, float]:
+ """The height each Z-type axis (the channels' and the gripper's GZ) travels at by default, cm
+ of its bottom above the deck: its ceiling (`_traverse_ceilings`), or
+ `default_minimum_traverse_height` where that is lower."""
+ ceilings = self._traverse_ceilings()
+ wanted = units.optional_cm(self.default_minimum_traverse_height)
+ return {
+ name: top if wanted is None or name == "GZ" else min(wanted, top)
+ for name, top in ceilings.items()
+ }
+
+ def _traverse_ceilings(self) -> Dict[str, float]:
+ """The highest each Z-type axis travels, cm of its bottom above the deck: the top of travel less
+ the park margin (`ParkLocation` `ZMargin`, `GZMargin`), as Biomek parks them (the
+ Multichannel's rest Z, 39.763 cm, is -256 counts). A Span-8 probe goes no higher than its top
+ less `DiscardOffset`: above that its stripper pushes a tip off (Biomek travels carrying probes
+ there, as its logs show)."""
+ d = self._require_declared()
+ shuck = d.settings.get("DiscardOffset") if self.module_type == "span8" else None
+ ceilings = {}
+ for name in self.channel_z_axes + ["GZ"]:
+ top = d.limits[name][1]
+ ceiling = top + d.park.get("GZMargin" if name == "GZ" else "ZMargin", 0.0)
+ if shuck is not None and name != "GZ":
+ ceiling = min(ceiling, top - shuck)
+ ceilings[name] = ceiling
+ return ceilings
+
+ async def park(self) -> None:
+ """Biomek's park (`_park`): the channels and the gripper raised, the pod to its park X and Y,
+ the gripper turned and closed to its park."""
+ await self._park()
+
+ async def _park(self, over: Optional[Mapping[str, int]] = None) -> None:
+ """Biomek's park (`ParkLocation`): the channels and the gripper raised to their ceilings
+ (`_traverse_ceilings`), the pod to the park X (`XMargin` in from its own end of the rail) and
+ `Y`, the gripper turned and closed to its park (`GR`, `GY`, then `GG`). As logged after a
+ prime (2026-10-09), to the count. `over`: X/Y targets (counts) for a pod whose park declares
+ none. Without either, it parks where it stands.
+
+ Raises:
+ RuntimeError: without a declared configuration.
+ """
+ d = self.declared
+ if d is None:
+ raise RuntimeError(f"{self} needs a declared configuration")
+ if self._held_labware is not None:
+ raise RuntimeError(f"{self}: the gripper holds labware; place it before parking")
+ p = d.park
+ targets: Dict[str, int] = dict(over or {})
+ if "XMargin" in p and "X" not in targets:
+ low, high = d.limits["X"]
+ x = low + p["XMargin"] if self.side == "left" else high - p["XMargin"]
+ targets["X"] = d.to_counts("X", x)
+ if "Y" in p and "Y" not in targets:
+ targets["Y"] = d.to_counts("Y", p["Y"])
+ targets.update({a: d.to_counts(a, p[a]) for a in ("GR", "GY") if a in p})
+ await self._move_over(targets)
+ # The channels rest at the top less the park margin, and on a Span-8 less `DiscardOffset` as
+ # well (39.1079 cm on Z1, 9029 counts: lower than the probes travel, `_traverse_ceilings`).
+ shuck = d.settings.get("DiscardOffset", 0.0) if self.module_type == "span8" else 0.0
+ rest = {
+ z: d.to_counts(z, d.limits[z][1] + p.get("ZMargin", 0.0) - shuck) for z in self.channel_z_axes
+ }
+ if any(self.cpositions[z][1] != c for z, c in rest.items()):
+ await self.move_axes(rest)
+ if "GG" in p:
+ # Closed under the grip force, as Biomek's park closes it (it may stop on its own fingers).
+ force = d.settings["GripperSqueezeForce"]
+ await self.move_axes({"GG": d.to_counts("GG", p["GG"])}, forces={"GG": force})
+ # The force leaves GG's position unknown, and the rail counts an unknown gripper as every
+ # pose it could take, in the other pod's way: read it back now.
+ await self._read_unknown_positions()
+
+ async def move_aside(self) -> None:
+ """Raise the pod and take it to the end of its X travel on its own side (the left pod to its
+ lowest X, the right pod to its highest), leaving the other pod the most of the rail. Biomek
+ moves a pod out of the way itself; the rail guard here refuses instead
+ (`x_rail.py`), so a caller makes room with this.
+
+ Raises:
+ RuntimeError: without a declared configuration.
+ """
+ d = self.declared
+ if d is None:
+ raise RuntimeError(f"{self} needs a declared configuration")
+ low, high = d.limits["X"]
+ await self._move_over({"X": d.to_counts("X", low if self.side == "left" else high)})
+
+ async def _move_over(
+ self,
+ targets: Mapping[str, int],
+ speed: int = 1000,
+ minimum_traverse_height: Optional[float] = None,
+ z_final: Optional[float] = None,
+ clearance: Optional[float] = None,
+ allow_below_clearance: bool = False,
+ tip_lengths: Optional[Mapping[str, float]] = None,
+ gripper_height: Optional[float] = None,
+ ) -> MoveResult:
+ """Travel to `targets` (X, Y and the like, in counts, as `move_axes` takes them) clear of the
+ deck: lift the channels and the gripper to a traverse height, move, then optionally set the
+ channels to `z_final`. STAR's `minimum_traverse_height_at_beginning_of_a_command` and
+ `z_final`, and Biomek's Safe Height; design.md I12. Heights here are Biomek's frame, cm above
+ the deck surface, and are each channel's lowest point, as STAR's are: the end of the tip it
+ carries (`tip_lengths`), else its bottom. An axis already above its traverse height is not
+ lowered.
+
+ Args:
+ targets: the travel's targets; channel Z axes in them are refused (use `z_final`).
+ speed: as `move_axes`, for every step.
+ minimum_traverse_height: the channels' lowest points while traveling. Default: each channel
+ at `_traverse_heights` (as high as it goes). The gripper travels at its default
+ always.
+ z_final: where to set the channels' bottoms once there; None leaves them at the traverse
+ height.
+ clearance: the lowest height the deck under the path allows, from a deck model, if known.
+ allow_below_clearance: travel lower than `clearance` and the obstacles allow, deliberately.
+ tip_lengths: per channel Z axis, how far below its bottom the tip it carries ends, cm; none
+ when None.
+ gripper_height: GZ (cm) to travel at. Default: its traverse height, no higher than clears
+ the pod's own pipettor for the travel's GR (`_gripper_traverse_height`).
+
+ Raises:
+ ValueError: for a channel Z axis in `targets`; for a path through a wall (a shield, a
+ tower, the light curtain); for a traverse height below what the path needs (unless
+ `allow_below_clearance`), a need above what the channels reach, or a height a channel
+ cannot lift its tip to (under its `_traverse_ceilings`). Nothing is sent.
+ """
+ d = self._require_declared()
+ channels = self.channel_z_axes
+ stray = sorted(set(targets) & set(channels))
+ if stray:
+ raise ValueError(f"{self}: {stray} in a travel's targets; use z_final")
+ lengths = {} if tip_lengths is None else dict(tip_lengths)
+ await self._read_unknown_positions()
+ area = self._travel_area(targets)
+ need = g.obstacle_clearance(d.obstacles, *area)
+ if need.walls:
+ raise ValueError(f"{self}: the travel would pass through {', '.join(need.walls)}")
+ required = max(need.height, -math.inf if clearance is None else clearance)
+ heights, reach, traverse = self._traverse_targets(minimum_traverse_height, lengths)
+ if required > reach:
+ raise ValueError(f"{self}: the path needs {required:.3f} cm, above what the channels reach")
+ if traverse < required and not allow_below_clearance:
+ raise ValueError(
+ f"{self}: traverse height {traverse:.3f} cm is below the {required:.3f} cm the path needs;"
+ " pass allow_below_clearance=True to travel lower deliberately"
+ )
+ if gripper_height is None:
+ # No higher than clears the pod's own pipettor for the gripper's angle, and its turn if the
+ # travel turns it; only that lowers it (an axis above its traverse height stays there).
+ gr = d.to_value("GR", targets.get("GR", self._cpositions["GR"][1]))
+ clear = self._gripper_traverse_height(gr)
+ if clear < heights["GZ"]:
+ gripper_height = clear
+ if gripper_height is not None:
+ heights["GZ"] = gripper_height
+ if d.to_counts("GZ", gripper_height) < self._cpositions["GZ"][1]:
+ await self.move_axes({"GZ": d.to_counts("GZ", gripper_height)}, speed)
+ await self._raise_to(heights, speed)
+ result = await self.move_axes(targets, speed)
+ if z_final is not None:
+ await self.move_axes({n: d.to_counts(n, z_final) for n in channels}, speed)
+ return result
+
+ async def move_over(
+ self,
+ targets: Mapping[str, float],
+ speed_fraction: float = 1.0,
+ minimum_traverse_height: Optional[float] = None,
+ z_final: Optional[float] = None,
+ clearance: Optional[float] = None,
+ allow_below_clearance: bool = False,
+ tip_lengths: Optional[Mapping[str, float]] = None,
+ gripper_height: Optional[float] = None,
+ ) -> MoveResult:
+ """Travel to `targets` clear of the deck: lift the channels and the gripper to a traverse
+ height, move, then optionally set the channels to `z_final` (STAR's
+ `minimum_traverse_height_at_beginning_of_a_command` and `z_final`; Biomek's Safe Height).
+ Heights are mm above the deck of each channel's lowest point, as STAR's are: the end of the
+ tip it carries, else its bottom. An axis already above its traverse height is not lowered.
+
+ Args:
+ targets: per axis, in PyLabRobot's units (`units.axis_to_biomek`): X and Y as deck x / y
+ (mm) of the point the pod's X and Y name (mandrel A1, probe 1), S (the Span-8's span) and
+ GG in mm, GR in degrees, pumps in uL. Channel Z axes are refused (use `z_final`).
+ speed_fraction: the share of each axis's maximum velocity every step moves at, (0, 1]: one
+ for the whole move, as the instrument has.
+ minimum_traverse_height: the channels' lowest points while traveling, mm. Default: each at
+ `traverse_heights`.
+ z_final: where to set the channels' bottoms once there, mm; None leaves them at the traverse
+ height.
+ clearance: the lowest height the deck under the path allows, mm (`traverse_clearance`).
+ allow_below_clearance: travel lower than `clearance` and the obstacles allow, deliberately.
+ tip_lengths: per channel Z axis, how far below its bottom the tip it carries ends, mm. The
+ pod's own record when None (`carried_tip_lengths`).
+ gripper_height: GZ, mm, to travel at. Default: its traverse height, no higher than clears
+ the pod's own pipettor.
+
+ Raises:
+ ValueError: as `_move_over`, its Biomek-unit counterpart; for a `speed_fraction` outside
+ (0, 1]. Nothing is sent.
+ """
+ return await self._move_over(
+ {axis: units.axis_to_counts(self, axis, value) for axis, value in targets.items()},
+ units.fraction_to_field(speed_fraction),
+ minimum_traverse_height=units.optional_cm(minimum_traverse_height),
+ z_final=units.optional_cm(z_final),
+ clearance=units.optional_cm(clearance),
+ allow_below_clearance=allow_below_clearance,
+ tip_lengths=(
+ None if tip_lengths is None else {a: units.to_cm(v) for a, v in tip_lengths.items()}
+ ),
+ gripper_height=units.optional_cm(gripper_height),
+ )
+
+ def traverse_heights(self) -> Dict[str, float]:
+ """The height each Z-type axis (the channels' and the gripper's GZ) travels at by default, mm
+ of its bottom above the deck: its ceiling (`traverse_ceilings`), or
+ `default_minimum_traverse_height` where that is lower."""
+ return {axis: units.to_mm(v) for axis, v in self._traverse_heights().items()}
+
+ def traverse_ceilings(self) -> Dict[str, float]:
+ """The highest each Z-type axis travels, mm of its bottom above the deck (`_traverse_ceilings`)."""
+ return {axis: units.to_mm(v) for axis, v in self._traverse_ceilings().items()}
+
+ def _traverse_targets(
+ self, minimum_traverse_height: Optional[float], tip_lengths: Mapping[str, float]
+ ) -> Tuple[Dict[str, float], float, float]:
+ """Where each Z-type axis's bottom goes to travel, cm; the highest every channel's lowest point
+ reaches; and how high the lowest one travels. By default each at `_traverse_heights`
+ (defined on the bottoms: the tips do not change where they go); given a height, the channels'
+ lowest points there (a channel's bottom at the height + its tip's length, `tip_lengths`).
+
+ Raises:
+ ValueError: for a height a channel cannot lift its tip to.
+ """
+ channels = self.channel_z_axes
+ lengths = {n: tip_lengths.get(n, 0.0) for n in channels}
+ heights = self._traverse_heights()
+ ceilings = self._traverse_ceilings()
+ reach = min(ceilings[n] - lengths[n] for n in channels)
+ if minimum_traverse_height is None:
+ return heights, reach, min(heights[n] - lengths[n] for n in channels)
+ short = {
+ n: round(ceilings[n] - lengths[n], 4)
+ for n in channels
+ if minimum_traverse_height + lengths[n] > ceilings[n] + 1e-9
+ }
+ if short:
+ raise ValueError(
+ f"{self}: traverse height {minimum_traverse_height:.3f} cm is above what the channels"
+ f" reach with their tips: {short}"
+ )
+ heights.update({n: minimum_traverse_height + lengths[n] for n in channels})
+ return heights, reach, minimum_traverse_height
+
+ async def _lift_channels(
+ self,
+ minimum_traverse_height: Optional[float] = None,
+ tip_lengths: Optional[Mapping[str, float]] = None,
+ speed: int = 1000,
+ ) -> None:
+ """Raise the channels (not the gripper) where they stand to a traverse height, as `_move_over`
+ does before traveling (the same meaning of heights, the same tips); never lower.
+
+ Raises:
+ ValueError: for a height a channel cannot lift its tip to. Nothing is sent.
+ """
+ lengths = {} if tip_lengths is None else tip_lengths
+ heights, _, _ = self._traverse_targets(minimum_traverse_height, lengths)
+ await self._read_unknown_positions()
+ await self._raise_to({n: heights[n] for n in self.channel_z_axes}, speed)
+
+ async def _raise_to(self, heights: Mapping[str, float], speed: int) -> None:
+ """Move the axes below their `heights` (cm) up to them, together."""
+ d = self._require_declared()
+ lift = {}
+ for name, height in heights.items():
+ counts = d.to_counts(name, height)
+ if self._cpositions[name][1] < counts: # counts grow with height on every Z-type axis
+ lift[name] = counts
+ if lift:
+ await self.move_axes(lift, speed)
+
+ def _travel_area(self, targets: Mapping[str, int]) -> Tuple[g.Range, g.Range]:
+ """The X/Y area the pod's body covers from where it is to `targets`, cm."""
+ d = self._require_declared()
+ y_axis = "Y" if self.module_type == "multichannel" else "Y1"
+ x0 = d.to_value("X", self._cpositions["X"][1])
+ y0 = d.to_value("Y", self._cpositions[y_axis][1])
+ x1 = d.to_value("X", targets.get("X", self._cpositions["X"][1]))
+ y1 = d.to_value("Y", targets.get("Y", targets.get(y_axis, self._cpositions[y_axis][1])))
+ (ax, ay), (bx, by) = g.pod_xy_box(d.geometry, x0, y0), g.pod_xy_box(d.geometry, x1, y1)
+ return g.union(ax, bx), g.union(ay, by)
+
+ async def _send_motions(
+ self,
+ motions: Sequence[motion.Motion],
+ timeout_ms: int,
+ forces: Mapping[str, float],
+ sensors: Mapping[str, Tuple[int, int]],
+ ) -> Dict[str, p.MotionComplete]:
+ """Set each motion's parameters, then start them together and wait for them to finish.
+ Returns, per axis, its report when it was not a plain finish.
+
+ The parameters go out in the order the Master Controller's requests reach the board
+ (`motion.spawn_order`), motors and pumps together, so a session's traffic lines up with
+ Biomek's request for request."""
+ moves = []
+ for m in motion.spawn_order(motions):
+ sensor, trigger = sensors.get(m.axis, (0, 0))
+ moves.append(
+ AxisMove(
+ m.axis,
+ m.position,
+ m.velocity,
+ m.acceleration,
+ m.jerk or 0,
+ round(forces.get(m.axis, 0.0) * 1000),
+ sensor,
+ trigger,
+ )
+ )
+ accepted = await self._unchecked_fw_set_move_parameters(moves)
+ if not all(accepted):
+ await self._unchecked_fw_stop_motion()
+ refused = [m.axis for m, ok in zip(moves, accepted) if not ok]
+ raise NotHomedError(0x32, None, f"{self}: {refused} not homed")
+ reports = await self._unchecked_fw_move_all(timeout_ms)
+ names = {(a.device, a.index): a.name for a in self.axes}
+ return {
+ names[(c.device, c.index)]: c
+ for c in reports
+ if (c.device, c.index) in names and c.outcome != "done"
+ }
+
+ # -- drive commands ----------------------------------------------------------
+ # The only way this driver commands a drive: one request, or one batch sent together, each. They
+ # check targets against the axis's limits and nothing else. Whether an axis may move now (homed,
+ # interlock armed, clear of the other pod) is the caller's to decide, as homing does by asking
+ # the board.
+
+ async def _unchecked_fw_enable(self, axes: Sequence[str]) -> None:
+ """Set State ENABLED on each axis, sent together. On a drive in fault this is also the fault
+ reset; one that cannot come up answers an error and stays in fault."""
+ if axes:
+ targets = [self.axis(name) for name in axes]
+ await self.board.send_many(
+ [p.set_state_enabled(a.device, a.index) for a in targets],
+ timeout=5.0 + ENABLE_SECONDS_PER_AXIS * len(targets),
+ )
+
+ async def _unchecked_fw_set_move_parameters(self, moves: Sequence[AxisMove]) -> List[bool]:
+ """Set each axis's next move, sent together in the order given. Returns, per move, whether the
+ board took it (True) or refused it because the axis has not been homed since power-up (False).
+
+ A syringe pump's move is sent as the Span-8's `move` does: the pump's minimum start velocity,
+ the move's velocity and acceleration, the cutoff velocity clamped to the pump's range, and the
+ valve as last set; its jerk, force and sensor are not sent.
+
+ Raises:
+ ValueError: for a target outside the axis's limits; nothing is sent.
+ RuntimeError: for a pump whose valve has not been set; nothing is sent.
+ AceError: for any refusal other than "not homed".
+ """
+ requests = []
+ for move in moves:
+ axis = self.axis(move.axis)
+ axis.check_position(move.position)
+ limits = axis.limits
+ velocity = limits.max_velocity if move.velocity is None else move.velocity
+ acceleration = limits.max_acceleration if move.acceleration is None else move.acceleration
+ if axis.is_pump:
+ valve = self._valves[move.axis]
+ if valve is None:
+ raise RuntimeError(f"{self}: {move.axis}'s valve has not been set")
+ pump = axis.pump_limits
+ cutoff = int(
+ motion.range_(pump.min_cutoff_velocity, self._cutoff_velocity, pump.max_cutoff_velocity)
+ )
+ requests.append(
+ p.set_pump_move_parameters(
+ axis.index,
+ move.position,
+ pump.min_start_velocity,
+ velocity,
+ cutoff,
+ acceleration,
+ valve,
+ )
+ )
+ continue
+ requests.append(
+ p.set_motor_move_parameters(
+ axis.index,
+ move.position,
+ velocity,
+ acceleration,
+ limits.max_jerk if move.jerk is None else move.jerk,
+ move.force,
+ move.sensor,
+ move.trigger,
+ )
+ )
+ replies = await self.board.send_many(requests, raise_errors=False)
+ accepted = []
+ for move, reply in zip(moves, replies):
+ try:
+ reply.raise_for_error(f"{self}: Set {move.axis} Move Parameters")
+ accepted.append(True)
+ except NotHomedError:
+ accepted.append(False)
+ return accepted
+
+ async def _unchecked_fw_move(self, axis: str, timeout_ms: int = MOVE_TIMEOUT_MS) -> None:
+ """Start one axis's move to the parameters set for it, and wait for it to finish."""
+ await self.board.send(
+ p.move(self.axis(axis).index, timeout_ms), timeout=timeout_ms / 1000 + 5.0
+ )
+
+ async def _unchecked_fw_move_all(
+ self, timeout_ms: int = MOVE_ALL_TIMEOUT_MS
+ ) -> List[p.MotionComplete]:
+ """Start every axis whose move parameters were set since its last move, together, and wait for
+ all of them to finish. Returns the reports the axes sent under the Move All."""
+ reply = await self.board.send(p.move_all(timeout_ms), timeout=timeout_ms / 1000 + 5.0)
+ return [p.parse_motion_complete(r) for r in reply.related]
+
+ async def _unchecked_fw_home(self, axes: Sequence[str]) -> None:
+ """Home the axes, sent together, and wait for every one to finish."""
+ targets = [self.axis(name) for name in axes]
+ await self.board.send_many(
+ [p.home(a.device, a.index) for a in targets], timeout=HOME_REPLY_TIMEOUT
+ )
+
+ async def _unchecked_fw_stop_motion(self) -> None:
+ """Stop Motion Service on this pod's board: stops every axis and drops pending moves."""
+ await self.board.send(p.stop_motion_service())
+
+ async def _unchecked_fw_configure(self, axis: Axis) -> None:
+ """Load one axis's motor table (Configure). Leaves it disabled and not homed."""
+ await self.board.send(p.configure(axis.device, axis.index, axis.configure))
+
+ async def _unchecked_fw_stop_module_execution(self) -> None:
+ await self.board.send(p.stop_module_execution())
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/framing.py b/pylabrobot/beckman_coulter/biomek_i7/driver/framing.py
new file mode 100644
index 00000000000..5407f0f16c6
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/framing.py
@@ -0,0 +1,100 @@
+"""ACE framing: how messages travel in the Biomek i7's USB transfers.
+
+Every message travels as a frame, a length byte followed by that many message bytes::
+
+ length (1) | message (length)
+
+The host packs one or more frames into an interrupt OUT transfer on endpoint 0x02 (32-byte
+packets) and sends no zero-length packet after one that fills its last packet. A board sends one
+frame per interrupt IN transfer on endpoint 0x81 (16-byte packets); a frame longer than 15 bytes
+spans several packets. Established on a cold start captured with USBPcap, 2026-10-24: all 3,507
+transfers split into whole frames.
+"""
+
+from typing import Iterable, List
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import FrameError
+
+# The largest OUT transfer the Master Controller sent in the captured cold start. Larger ones are
+# not known to be accepted, so frames are packed no further than this.
+MAX_OUT_TRANSFER = 253
+
+# The IN endpoint's packet size: one read returns at most one packet.
+IN_PACKET_SIZE = 16
+
+
+def frame(message: bytes) -> bytes:
+ """Prefix one message with its length byte.
+
+ Raises:
+ ValueError: if the message is empty or longer than 255 bytes.
+ """
+ if not 0 < len(message) <= 0xFF:
+ raise ValueError(f"an ACE message is 1-255 bytes, got {len(message)}")
+ return bytes([len(message)]) + message
+
+
+def pack(messages: Iterable[bytes], max_transfer: int = MAX_OUT_TRANSFER) -> List[bytes]:
+ """Pack messages, in order, into as few OUT transfers as fit `max_transfer` bytes each."""
+ transfers: List[bytes] = []
+ current = b""
+ for message in messages:
+ framed = frame(message)
+ if len(framed) > max_transfer:
+ raise ValueError(f"a {len(framed)}-byte frame does not fit a {max_transfer}-byte transfer")
+ if len(current) + len(framed) > max_transfer:
+ transfers.append(current)
+ current = b""
+ current += framed
+ if current:
+ transfers.append(current)
+ return transfers
+
+
+def split(transfer: bytes) -> List[bytes]:
+ """Split one whole transfer into its messages.
+
+ Raises:
+ FrameError: if the transfer does not end on a frame boundary, or holds an empty frame.
+ """
+ reader = FrameReader()
+ messages = reader.feed(transfer)
+ if reader.pending:
+ raise FrameError(f"transfer ends inside a frame: {transfer.hex()}")
+ return messages
+
+
+class FrameReader:
+ """Reassemble frames from IN packets, which may end anywhere inside a frame."""
+
+ def __init__(self) -> None:
+ self._buffer = bytearray()
+
+ @property
+ def pending(self) -> int:
+ """How many bytes of an unfinished frame are held."""
+ return len(self._buffer)
+
+ def feed(self, data: bytes) -> List[bytes]:
+ """Take the next bytes read and return every message they complete.
+
+ Raises:
+ FrameError: on a zero length byte, which no board sends and which would never advance.
+ """
+ self._buffer += data
+ messages: List[bytes] = []
+ while self._buffer:
+ length = self._buffer[0]
+ if length == 0:
+ bad = bytes(self._buffer)
+ self._buffer.clear()
+ raise FrameError(f"zero-length frame in {bad.hex()}")
+ if len(self._buffer) < length + 1:
+ break
+ messages.append(bytes(self._buffer[1 : length + 1]))
+ del self._buffer[: length + 1]
+ return messages
+
+ def reset(self) -> None:
+ """Drop an unfinished frame, as after a read error."""
+ self._buffer.clear()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/framing_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/framing_tests.py
new file mode 100644
index 00000000000..bb4663ce5ee
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/framing_tests.py
@@ -0,0 +1,118 @@
+"""ACE framing: length-prefixed messages, packed into OUT transfers and read back from 16-byte IN
+packets."""
+
+import random
+import unittest
+from typing import List
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import FrameError
+from pylabrobot.beckman_coulter.biomek_i7.driver.framing import (
+ IN_PACKET_SIZE,
+ MAX_OUT_TRANSFER,
+ FrameReader,
+ frame,
+ pack,
+ split,
+)
+
+# Transfers from a captured cold start, each as it went over the wire: three Set Move Parameters
+# packed into one OUT transfer, and three answers, each its own IN transfer, the last longer than a
+# packet (an analog input's name, "Temperature").
+CAPTURED_OUT = (
+ "1b1101001840150000001f0000003201000000000000038c00000000"
+ "1b1105001940030f0100298301009b1f0f000000000013f900000000"
+ "1b1102001a40b86f0200077b030044ce2200000000008a9100000000"
+)
+CAPTURED_IN = [
+ "09000000010002008000",
+ "0902010007030200e500",
+ "122209000b01020054656d7065726174757265",
+]
+
+
+def messages(rng: random.Random, count: int) -> List[bytes]:
+ return [bytes(rng.randrange(256) for _ in range(rng.randrange(1, 256))) for _ in range(count)]
+
+
+class CapturedTransferTests(unittest.TestCase):
+ def test_a_packed_out_transfer_splits_into_its_requests(self) -> None:
+ data = bytes.fromhex(CAPTURED_OUT)
+ requests = split(data)
+ self.assertEqual([(m[0], m[1], m[3], m[4]) for m in requests],
+ [(0x11, 1, 0x18, 0x40), (0x11, 5, 0x19, 0x40), (0x11, 2, 0x1A, 0x40)]) # fmt: skip
+ self.assertEqual(pack(requests), [data])
+
+ def test_in_transfers_hold_one_frame_each(self) -> None:
+ for hex_data in CAPTURED_IN:
+ data = bytes.fromhex(hex_data)
+ (message,) = split(data)
+ self.assertEqual(frame(message), data)
+
+
+class InverseTests(unittest.TestCase):
+ """Framing and splitting undo each other, for any messages."""
+
+ def setUp(self) -> None:
+ self.rng = random.Random(11)
+
+ def test_frame_then_split(self) -> None:
+ for message in messages(self.rng, 200) + [b"\x00", b"\xff" * 255]:
+ self.assertEqual(split(frame(message)), [message])
+
+ def test_pack_then_split_keeps_order_and_fits(self) -> None:
+ for _ in range(50):
+ batch = [m[: MAX_OUT_TRANSFER - 1] for m in messages(self.rng, self.rng.randrange(1, 12))]
+ transfers = pack(batch)
+ self.assertTrue(all(len(t) <= MAX_OUT_TRANSFER for t in transfers))
+ self.assertEqual([m for t in transfers for m in split(t)], batch)
+
+ def test_frames_reassemble_from_packets(self) -> None:
+ """Read packet by packet, as the board's reader does, the frames come out unchanged."""
+ reader = FrameReader()
+ for message in messages(self.rng, 200):
+ data = frame(message)
+ out: List[bytes] = []
+ for i in range(0, len(data), IN_PACKET_SIZE):
+ out += reader.feed(data[i : i + IN_PACKET_SIZE])
+ self.assertEqual(out, [message])
+ self.assertEqual(reader.pending, 0)
+
+ def test_frames_reassemble_from_any_cut(self) -> None:
+ stream = b"".join(frame(m) for m in messages(self.rng, 20))
+ for _ in range(20):
+ reader = FrameReader()
+ cuts = sorted(self.rng.sample(range(1, len(stream)), 15))
+ out: List[bytes] = []
+ for a, b in zip([0] + cuts, cuts + [len(stream)]):
+ out += reader.feed(stream[a:b])
+ self.assertEqual(out, split(stream))
+
+
+class PackTests(unittest.TestCase):
+ def test_packs_in_order_until_the_transfer_is_full(self) -> None:
+ messages = [bytes([i]) * 100 for i in range(3)]
+ transfers = pack(messages)
+ self.assertEqual(transfers, [frame(messages[0]) + frame(messages[1]), frame(messages[2])])
+ self.assertTrue(all(len(t) <= MAX_OUT_TRANSFER for t in transfers))
+
+ def test_rejects_empty_and_oversized_messages(self) -> None:
+ with self.assertRaises(ValueError):
+ frame(b"")
+ with self.assertRaises(ValueError):
+ frame(b"x" * 256)
+ with self.assertRaises(ValueError):
+ pack([b"x" * 255]) # a frame larger than a transfer
+
+ def test_split_rejects_a_truncated_transfer(self) -> None:
+ with self.assertRaises(FrameError):
+ split(bytes([5, 1, 2]))
+
+ def test_zero_length_frame_is_an_error(self) -> None:
+ reader = FrameReader()
+ with self.assertRaises(FrameError):
+ reader.feed(b"\x00\x01")
+ self.assertEqual(reader.pending, 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py
new file mode 100644
index 00000000000..9f21856d1ff
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py
@@ -0,0 +1,328 @@
+"""Home All against the generic instrument simulated: the requests each board is sent are the ones
+Biomek's Master Controller sent (the cold start the generic recording was made from; a forced Home
+All of a homed instrument, as its logs show it), and where each axis ends."""
+
+import asyncio
+import struct
+import unittest
+from typing import Dict, List
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver
+from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import HOME_RECIPES, Homer
+from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import SimulatedAceUSB
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import (
+ generic_driver,
+ generic_recording,
+ generic_simulated_boards,
+)
+
+SPAN8_Z = [f"Z{i}" for i in range(1, 9)]
+# Reads the driver sends that Biomek's logs of a Home All leave out: the reads Biomek never
+# sends (Get State, Get Interlock Status), and Read Analog/Digital Input (the drive supply and door
+# checks), which Biomek polls in the background.
+NOT_IN_RECORDINGS = set(p.FIRMWARE_READS) | {
+ (p.Device.ANALOG_INPUT, 0x10),
+ (p.Device.DIGITAL_INPUT, 0x10),
+}
+MASTER_LOGGER = "pylabrobot.beckman_coulter.biomek_i7.driver.master"
+READ_ONLY_SETUP = dict(skip_device_initialization=True, skip_left_x_arm=True, skip_right_x_arm=True)
+READS = ("Get ", "Read ", "List ")
+
+# The Multichannel board's requests in a forced Home All of a homed instrument (`HM`), as
+# Biomek's logs show it (2026-10-23): command, axis, and a move's target or a Move's timeout.
+FORCED_HM_MULTICHANNEL = [
+ ("Set State", "Z", None),
+ ("Set Move Parameters", "Z", -1000),
+ ("Move", "Z", 30000),
+ ("Home", "Z", None),
+ ("Set State", "GZ", None),
+ ("Set Move Parameters", "GZ", 0),
+ ("Move", "GZ", 30000),
+ ("Set State", "GG", None),
+ ("Set Move Parameters", "GG", 0),
+ ("Move", "GG", 30000),
+ ("Home", "GG", None),
+ ("Set State", "GG", None),
+ ("Set Move Parameters", "GG", 35753),
+ ("Move", "GG", 30000),
+ ("Set State", "GR", None),
+ ("Set Move Parameters", "GR", 0),
+ ("Move", "GR", 30000),
+ ("Home", "GR", None),
+ ("Set State", "GR", None),
+ ("Set Move Parameters", "GR", -212581),
+ ("Move", "GR", 30000),
+ ("Set State", "GR", None),
+ ("Set Move Parameters", "GR", -174956),
+ ("Move", "GR", 30000),
+ ("Set State", "GY", None),
+ ("Set Move Parameters", "GY", 0),
+ ("Move", "GY", 30000),
+ ("Home", "GY", None),
+ ("Set State", "GZ", None),
+ ("Set Move Parameters", "GZ", 0),
+ ("Move", "GZ", 30000),
+ ("Home", "GZ", None),
+ ("Set State", "GY", None),
+ ("Set Move Parameters", "GY", 47574),
+ ("Move", "GY", 30000),
+ ("Set State", "Y", None),
+ ("Set Move Parameters", "Y", 0),
+ ("Move", "Y", 30000),
+ ("Home", "Y", None),
+ ("Set State", "Y", None),
+ ("Set Move Parameters", "Y", 0),
+ ("Move", "Y", 30000),
+ ("Set State", "GR", None),
+ ("Set Move Parameters", "GR", -141093),
+ ("Move", "GR", 30000),
+ ("Set State", "X", None),
+ ("Set Move Parameters", "X", 0),
+ ("Move", "X", 30000),
+ ("Home", "X", None),
+ ("Set State", "X", None),
+ ("Set Move Parameters", "X", 35840),
+ ("Move", "X", 30000),
+]
+
+
+def zero_sequence(message: bytes) -> str:
+ return (message[:3] + b"\x00" + message[4:]).hex()
+
+
+def opcode_names(messages: List[str]) -> List[str]:
+ return [p.COMMANDS[(bytes.fromhex(h)[0], bytes.fromhex(h)[4])] for h in messages]
+
+
+class SimulatedRunTest(unittest.IsolatedAsyncioTestCase):
+ """What each simulated board was sent since a mark."""
+
+ marks: Dict[str, int]
+
+ async def asyncSetUp(self) -> None:
+ # IsolatedAsyncioTestCase runs its loop in debug mode, which records a stack for every
+ # callback and future; a simulated Home All makes thousands, and takes 3 s instead of 0.03 s.
+ # Nothing here is timed. The board-level tests keep debug mode's checks.
+ asyncio.get_running_loop().set_debug(False)
+
+ async def start(self, homed, configured=None, configuration=None) -> BiomekI7Driver:
+ """A driver on the generic instrument simulated, read but not brought up; `configuration`, a
+ declared configuration to use instead of the generic one (sealed)."""
+ driver = generic_driver(
+ generic_simulated_boards(homed=homed, configured=configured), configuration=configuration
+ )
+ await driver.setup(**READ_ONLY_SETUP)
+ self.addAsyncCleanup(driver.stop)
+ self.marks = {}
+ self.mark(driver)
+ return driver
+
+ def usb(self, driver: BiomekI7Driver, module: str) -> SimulatedAceUSB:
+ for board in driver.boards:
+ if board.name == f"simulated {module}":
+ assert isinstance(board.io, SimulatedAceUSB)
+ return board.io
+ raise KeyError(module)
+
+ def mark(self, driver: BiomekI7Driver) -> None:
+ for module in ("chassis", "multichannel", "span8"):
+ self.marks[module] = len(self.usb(driver, module).requests)
+
+ def since_mark(self, driver: BiomekI7Driver, module: str) -> List[str]:
+ """What a board was sent since the mark, without the reads Biomek's recordings leave out."""
+ requests = self.usb(driver, module).requests[self.marks[module] :]
+ return [zero_sequence(m) for m in requests if (m[0], m[4]) not in NOT_IN_RECORDINGS]
+
+
+class HomeAllTests(SimulatedRunTest):
+ async def test_a_cold_home_all_sends_what_the_recorded_cold_start_sent(self) -> None:
+ """From power-up (nothing configured or homed), setup configures and homes; every request each
+ pod's board is sent that is not a read is one the Master Controller sent at the cold start the
+ generic recording was made from, first sent in the same order."""
+ driver = generic_driver(generic_simulated_boards(homed=False, configured=False))
+ self.addAsyncCleanup(driver.stop)
+ await driver.setup()
+ recording = generic_recording()["boards"]
+ for module in ("multichannel", "span8"):
+ sent: List[str] = []
+ for m in self.usb(driver, module).requests:
+ key = (m[:3] + m[4:]).hex()
+ if not p.COMMANDS[(m[0], m[4])].startswith(READS) and key not in sent:
+ sent.append(key)
+ recorded = [
+ key
+ for key, _ in recording[module]
+ if not p.COMMANDS[(int(key[0:2], 16), int(key[6:8], 16))].startswith(READS)
+ ]
+ self.assertGreater(len(sent), 40, module)
+ self.assertEqual(sent, recorded[: len(sent)], module)
+
+ async def test_axes_end_where_biomek_leaves_them(self) -> None:
+ driver = await self.start(False)
+ await driver.configure()
+ await driver.home()
+ assert driver.left_x_arm and driver.right_x_arm
+ left = await driver.left_x_arm.request_positions()
+ self.assertEqual(
+ (left["X"], left["GY"], left["GG"], left["GR"]), (35840, 47574, 35753, -141093)
+ )
+ right = await driver.right_x_arm.request_positions()
+ self.assertEqual((right["X"], right["Z1"], right["Z8"]), (-2560, 9647, 9647))
+ for pod in driver.arms:
+ for axis in pod.axes:
+ if not axis.is_pump and axis.name != "D": # the plunger and pumps are homed apart (`HD`)
+ self.assertEqual(await pod.request_homed_state(axis.name), "homed", (pod.side, axis.name))
+
+
+class InitializeTests(SimulatedRunTest):
+ """`initialize`, which `setup` runs after discovery: homing forced or not, and refusals that come
+ before anything is written."""
+
+ async def start_initialized(self, homed, configured=None, **flags) -> BiomekI7Driver:
+ driver = await self.start(homed, configured)
+ await driver.initialize(**flags)
+ return driver
+
+ def written(self, driver: BiomekI7Driver) -> List[str]:
+ return [
+ name
+ for module in ("chassis", "multichannel", "span8")
+ for name in opcode_names(self.since_mark(driver, module))
+ if not name.startswith(("Get ", "Read ", "List "))
+ ]
+
+ async def test_forced_on_a_homed_instrument_is_biomeks_home_all(self) -> None:
+ driver = await self.start_initialized(True, force_initialize=True)
+ assert driver.left_x_arm is not None
+ names = {(a.device, a.index): a.name for a in driver.left_x_arm.axes}
+ sent = [bytes.fromhex(h) for h in self.since_mark(driver, "multichannel")]
+ decoded = []
+ for m in sent:
+ name = p.COMMANDS[(m[0], m[4])]
+ value = None
+ if name == "Set Move Parameters":
+ value = struct.unpack_from(" None:
+ forced = await self.start_initialized(True, force_initialize=True)
+ forced_sent = {m: self.since_mark(forced, m) for m in ("multichannel", "span8")}
+ driver = await self.start_initialized(True)
+ names = self.written(driver)
+ self.assertNotIn("Configure", names)
+ self.assertNotIn("Home", names)
+ for module in ("multichannel", "span8"):
+ sent = self.since_mark(driver, module)
+ # Every move is one Biomek makes, in Biomek's order: the default only leaves homes out.
+ moves = [h for h in sent if bytes.fromhex(h)[4] == 0x40]
+ forced_moves = [h for h in forced_sent[module] if bytes.fromhex(h)[4] == 0x40]
+ it = iter(forced_moves)
+ self.assertTrue(all(m in it for m in moves), module)
+ assert driver.left_x_arm and driver.right_x_arm
+ left = await driver.left_x_arm.request_positions()
+ self.assertEqual(
+ (left["X"], left["GY"], left["GG"], left["GR"], left["Z"]),
+ (35840, 47574, 35753, -141093, -1000),
+ )
+ right = await driver.right_x_arm.request_positions()
+ self.assertEqual((right["X"], right["Z1"], right["Z8"]), (-2560, 9647, 9647))
+
+ def moves(self, driver: BiomekI7Driver) -> List[str]:
+ """Every Set Move Parameters, Move, Move All and Home sent since the mark."""
+ motion = {"Set Move Parameters", "Move", "Move All", "Home"}
+ return [
+ name
+ for module in ("multichannel", "span8")
+ for name in opcode_names(self.since_mark(driver, module))
+ if name in motion
+ ]
+
+ async def test_resume_moves_an_axis_pushed_by_hand_back(self) -> None:
+ driver = await self.start_initialized(True)
+ left = self.usb(driver, "multichannel")
+ await driver.pause()
+ x = left.axis_model("X")
+ paused_at = x.position
+ x.position += 2000 # pushed by hand while the drives had no power
+ await driver.resume()
+ self.assertEqual(x.position, paused_at)
+
+ async def test_no_pod_moves_beside_a_skipped_pod_whose_x_is_not_homed(self) -> None:
+ for flags in (
+ dict(skip_right_x_arm=True),
+ dict(skip_device_initialization=True), # the right pod is left out, unconfigured
+ ):
+ with self.subTest(**flags):
+ driver = await self.start(
+ {"multichannel": ["X"]}, configured={"multichannel": True, "span8": False}
+ )
+ with self.assertRaisesRegex(RuntimeError, "shared X rail"):
+ await driver.initialize(**flags)
+ self.assertEqual(self.written(driver), [])
+
+ async def test_a_skipped_pod_with_x_homed_is_left_alone(self) -> None:
+ driver = await self.start_initialized(True, skip_right_x_arm=True)
+ self.assertEqual(
+ [n for n in opcode_names(self.since_mark(driver, "span8")) if not n.startswith("Get ")], []
+ )
+ self.assertIn("Move", opcode_names(self.since_mark(driver, "multichannel")))
+
+ async def test_setup_brings_the_instrument_up(self) -> None:
+ driver = generic_driver(generic_simulated_boards())
+ self.addAsyncCleanup(driver.stop)
+ await driver.setup()
+ assert driver.right_x_arm
+ self.assertEqual(await driver.right_x_arm.request_homed_state("Y4"), "homed")
+ await driver.setup() # repeatable: an instrument that is up is left up
+ self.assertEqual(await driver.right_x_arm.request_homed_state("Y4"), "homed")
+
+
+class RecipeTests(unittest.TestCase):
+ def setUp(self) -> None:
+ async def discover() -> list:
+ driver = generic_driver()
+ await driver.discover()
+ await driver.stop()
+ return list(driver.arms)
+
+ self.pods = {pod.module_type: pod for pod in asyncio.run(discover())}
+
+ def test_every_target_is_within_the_axis_limits(self) -> None:
+ for module, steps in HOME_RECIPES.items():
+ pod = self.pods[module]
+ homer = Homer(pod)
+ for step in steps:
+ for name, target in homer.targets(step):
+ pod.axis(name).check_position(target)
+
+ def test_post_home_targets_are_the_recorded_home_positions(self) -> None:
+ """Where a recipe leaves X, the left Y and the gripper axes is the Master Controller's `phome`
+ for them, as the motor recording carries it."""
+ for module, steps in HOME_RECIPES.items():
+ pod = self.pods[module]
+ homer = Homer(pod)
+ last: Dict[str, int] = {}
+ for step in steps:
+ for name, target in homer.targets(step):
+ last[name] = target
+ for name in ("X", "GY", "GG", "GR") + (("Y",) if module == "multichannel" else ()):
+ self.assertEqual(last[name], pod.axis(name).home_position, (module, name))
+
+ def test_the_gripper_turns_from_its_home_position(self) -> None:
+ # Home, then 190 and 90 degrees from the home position, then the home position: the counts
+ # Biomek's homes sent.
+ for module, pod in self.pods.items():
+ homer = Homer(pod)
+ turns = [t for step in HOME_RECIPES[module] for n, t in homer.targets(step) if n == "GR"]
+ self.assertEqual(turns, [0, -212581, -174956, -141093], module)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/lifecycle_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/lifecycle_tests.py
new file mode 100644
index 00000000000..9d438edf10d
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/lifecycle_tests.py
@@ -0,0 +1,380 @@
+"""Configure, the interlock, faults, pause / resume and stop, against the generic instrument
+simulated: what the driver sends, and how it handles what the boards answer. Nothing here moves an
+axis."""
+
+import asyncio
+import unittest
+from typing import Any, Dict, List
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError
+from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver
+from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import SimulatedAceUSB
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import (
+ generic_driver,
+ generic_recording,
+ generic_simulated_boards,
+)
+
+MASTER_LOGGER = "pylabrobot.beckman_coulter.biomek_i7.driver.master"
+MODULES = ("chassis", "multichannel", "span8")
+READ_ONLY_SETUP = dict(skip_device_initialization=True, skip_left_x_arm=True, skip_right_x_arm=True)
+
+
+def zero_sequence(message: bytes) -> str:
+ return (message[:3] + b"\x00" + message[4:]).hex()
+
+
+def name_of(message: bytes) -> str:
+ return p.COMMANDS[(message[0], message[4])]
+
+
+class SimulatedTest(unittest.IsolatedAsyncioTestCase):
+ """A driver on the generic instrument simulated, and what each board was sent since a mark."""
+
+ marks: Dict[str, int]
+
+ async def asyncSetUp(self) -> None:
+ asyncio.get_running_loop().set_debug(False) # the test loop's debug mode makes runs slow
+
+ async def start(self, homed: Any = True, configured: Any = None) -> BiomekI7Driver:
+ driver = generic_driver(generic_simulated_boards(homed=homed, configured=configured))
+ await driver.setup(**READ_ONLY_SETUP)
+ self.addAsyncCleanup(driver.stop)
+ self.marks = {}
+ self.mark(driver)
+ return driver
+
+ async def start_initialized(self, homed: Any = True, configured: Any = None, **flags: Any): # type: ignore[no-untyped-def]
+ driver = await self.start(homed, configured)
+ await driver.initialize(**flags)
+ return driver
+
+ def usb(self, driver: BiomekI7Driver, module: str) -> SimulatedAceUSB:
+ for board in driver.boards:
+ if board.name == f"simulated {module}":
+ assert isinstance(board.io, SimulatedAceUSB)
+ return board.io
+ raise KeyError(module)
+
+ def mark(self, driver: BiomekI7Driver) -> None:
+ for module in MODULES:
+ self.marks[module] = len(self.usb(driver, module).requests)
+
+ def sent(self, driver: BiomekI7Driver, module: str) -> List[bytes]:
+ return self.usb(driver, module).requests[self.marks[module] :]
+
+ def names(self, driver: BiomekI7Driver, module: str) -> List[str]:
+ return [name_of(m) for m in self.sent(driver, module)]
+
+ def written(self, driver: BiomekI7Driver) -> List[str]:
+ """Every request since the mark that is not a read."""
+ return [
+ name
+ for module in MODULES
+ for name in self.names(driver, module)
+ if not name.startswith(("Get ", "Read ", "List "))
+ ]
+
+ async def settle(self) -> None:
+ """Let the boards' read loops and the driver's background writes run."""
+ for _ in range(5):
+ await asyncio.sleep(0.02)
+
+
+class SimulatorRuleTests(SimulatedTest):
+ """The simulated boards answer as the instrument's did."""
+
+ async def test_an_axis_is_configured_before_it_takes_a_state(self) -> None:
+ driver = await self.start(homed=False, configured=False)
+ pod = driver.left_x_arm
+ assert pod is not None
+ with self.assertRaisesRegex(AceError, "not configured"):
+ await pod._unchecked_fw_enable(["Y"])
+ await pod._unchecked_fw_configure(pod.axis("Y"))
+ self.assertEqual((await pod.request_axis_states())["Y"], "disabled")
+ self.assertEqual(await pod.request_homed_state("Y"), "not_homed")
+
+ async def test_at_rest_cia402_drives_are_in_fault_and_refuse_enabling(self) -> None:
+ driver = await self.start()
+ left, right = driver.left_x_arm, driver.right_x_arm
+ assert left is not None and right is not None
+ self.assertEqual(set((await left.request_axis_states()).values()), {"fault"})
+ self.assertEqual((await right.request_axis_states())["Z1"], "enabled") # a SAGIAN drive
+ with self.assertRaisesRegex(AceError, "interlock tripped"):
+ await left._unchecked_fw_enable(["X"])
+ self.assertLess(await left.request_drive_supply(), 1.0)
+
+ async def test_armed_the_supply_comes_up_and_enabling_resets_a_fault(self) -> None:
+ driver = await self.start()
+ left = driver.left_x_arm
+ assert left is not None and driver.chassis is not None
+ await driver.chassis.arm_interlock()
+ self.assertGreater(await left.request_drive_supply(), 30.0)
+ await left._unchecked_fw_enable(["X"])
+ self.assertEqual((await left.request_axis_states())["X"], "enabled")
+ self.usb(driver, "multichannel").axis_model("Y").stuck_fault = True
+ with self.assertRaises(AceError) as caught:
+ await left._unchecked_fw_enable(["Y"])
+ self.assertEqual(caught.exception.code, 0x3D)
+
+
+class InitializeTests(SimulatedTest):
+ async def test_only_a_board_that_lost_its_tables_is_configured(self) -> None:
+ driver = await self.start_initialized(
+ homed={"multichannel": ["X"]}, configured={"multichannel": True, "span8": False}
+ )
+ self.assertNotIn("Configure", self.names(driver, "multichannel"))
+ assert driver.right_x_arm is not None
+ self.assertEqual(self.names(driver, "span8").count("Configure"), len(driver.right_x_arm.axes))
+ self.assertEqual(
+ self.names(driver, "chassis")[:3],
+ ["Trip Interlock", "Notify On Interlock Trip", "Set Status Display"],
+ )
+ states = await driver.request_axis_states()
+ self.assertEqual({s for pod in states.values() for s in pod.values()}, {"enabled"})
+
+ async def test_configure_sends_what_the_recorded_cold_start_sent(self) -> None:
+ """Each pod's Configure requests, and the chassis's interlock requests before them and the
+ I/O box write after, are the ones the Master Controller sent at the cold start the generic
+ recording comes from, in its order."""
+ driver = await self.start(homed=False, configured=False)
+ await driver.configure()
+ recording = generic_recording()["boards"]
+ for module in ("multichannel", "span8"):
+ recorded = [
+ key for key, _ in recording[module] if key[6:8] == "10" and key[:2] in ("11", "12")
+ ]
+ sent = [(m[:3] + m[4:]).hex() for m in self.sent(driver, module) if name_of(m) == "Configure"]
+ self.assertEqual(sent, recorded, module)
+ self.assertEqual(self.names(driver, module)[-1], "Stop Module Execution")
+ chassis = [(m[:3] + m[4:]).hex() for m in self.sent(driver, "chassis")]
+ recorded_keys = {key for key, _ in recording["chassis"]}
+ self.assertEqual(
+ self.names(driver, "chassis"),
+ ["Trip Interlock", "Notify On Interlock Trip", "Set Status Display", "Send Digital I/O Box"],
+ )
+ self.assertTrue(set(chassis) <= recorded_keys, set(chassis) - recorded_keys)
+
+ async def test_drives_at_rest_are_in_fault_and_enabling_clears_it(self) -> None:
+ driver = await self.start()
+ with self.assertLogs(MASTER_LOGGER, "INFO") as logs:
+ await driver.initialize()
+ self.assertTrue(any("as at rest" in line for line in logs.output))
+ self.assertFalse(any("collision" in line for line in logs.output))
+ self.assertNotIn("Configure", self.written(driver))
+ states = await driver.request_axis_states()
+ self.assertEqual({s for pod in states.values() for s in pod.values()}, {"enabled"})
+ self.assertFalse(driver.interlock_tripped.is_set())
+
+ async def test_enabling_follows_the_master_controllers_order(self) -> None:
+ driver = await self.start()
+ await driver.arm_interlock()
+ left = [m for m in self.sent(driver, "multichannel") if name_of(m) == "Set State"]
+ assert driver.left_x_arm is not None
+ names = {(a.device, a.index): a.name for a in driver.left_x_arm.axes}
+ self.assertEqual(
+ [names[(m[0], m[1])] for m in left], ["Z", "GZ", "GR", "GY", "GG", "Z", "D", "X", "Y"]
+ )
+
+ async def test_a_fault_under_power_is_reset_with_a_warning(self) -> None:
+ driver = await self.start()
+ usb = self.usb(driver, "multichannel")
+ usb.interlock.armed = True # left armed, by an earlier session
+ for model in usb.axes.values():
+ model.state = p.AxisState.ENABLED
+ usb.axis_model("Z").state = p.AxisState.FAULT
+ with self.assertLogs(MASTER_LOGGER, "WARNING") as logs:
+ await driver.initialize()
+ self.assertTrue(any(": Z in fault" in line and "collision" in line for line in logs.output))
+ self.assertEqual(usb.axis_model("Z").state, p.AxisState.ENABLED)
+
+ async def test_a_sagian_fault_is_warned_about_even_at_rest(self) -> None:
+ driver = await self.start()
+ self.usb(driver, "span8").axis_model("Z3").state = p.AxisState.FAULT
+ with self.assertLogs(MASTER_LOGGER, "WARNING") as logs:
+ await driver.initialize()
+ self.assertTrue(any("Z3" in line and "collision" in line for line in logs.output))
+
+ async def test_a_fault_that_does_not_clear_returns_the_instrument_to_rest(self) -> None:
+ driver = await self.start()
+ self.usb(driver, "multichannel").axis_model("Z").stuck_fault = True
+ with self.assertRaises(AceError):
+ await driver.initialize()
+ chassis = self.sent(driver, "chassis")
+ self.assertEqual([name_of(m) for m in chassis[-2:]], ["Trip Interlock", "Set Status Display"])
+ self.assertEqual(
+ zero_sequence(chassis[-1]), zero_sequence(p.set_status_display("error").encode(1))
+ )
+ self.assertFalse(self.usb(driver, "chassis").interlock.armed)
+ self.assertTrue(driver.interlock_tripped.is_set())
+
+ async def test_a_drive_supply_that_stays_off_stops_it_before_enabling(self) -> None:
+ driver = await self.start()
+ self.usb(driver, "chassis").interlock.supply_comes_up = False
+ with self.assertRaisesRegex(RuntimeError, "drive supply"):
+ await driver.initialize()
+ self.assertNotIn("Set State", self.written(driver))
+ self.assertFalse(self.usb(driver, "chassis").interlock.armed)
+
+ async def test_an_open_door_does_not_stop_it(self) -> None:
+ driver = await self.start()
+ chassis_usb = self.usb(driver, "chassis")
+ chassis_usb.interlock.door_open = True
+ assert driver.chassis and driver.front_cover
+ self.assertEqual(await driver.front_cover.request_state(), "open")
+ await driver.initialize() # Biomek arms with the door open
+ self.assertEqual(await driver.chassis.request_interlock_state(), "armed")
+
+ async def test_a_broken_light_curtain_stops_it(self) -> None:
+ driver = await self.start()
+ chassis_usb = self.usb(driver, "chassis")
+ chassis_usb.interlock.light_curtain_broken = True
+ with self.assertRaisesRegex(RuntimeError, "light curtain"):
+ await driver.initialize()
+ self.assertFalse(chassis_usb.interlock.armed)
+
+ async def test_door_changes_are_reported_and_the_light_curtain_trips_the_interlock(self) -> None:
+ driver = await self.start_initialized()
+ assert driver.chassis and driver.front_cover
+ await driver.front_cover.notify_changes()
+ seen: List[str] = []
+ driver.front_cover.subscribe(seen.append)
+ chassis_usb = self.usb(driver, "chassis")
+ chassis_usb.set_door(True)
+ await self.settle()
+ self.assertEqual(seen, ["open"])
+ self.assertEqual(await driver.chassis.request_interlock_state(), "armed")
+ chassis_usb.set_door(False)
+ await self.settle()
+ self.assertEqual(seen, ["open", "closed"])
+ with self.assertLogs(MASTER_LOGGER, "ERROR") as logs:
+ chassis_usb.set_light_curtain(True)
+ await self.settle()
+ self.assertIn("light curtain violation", "\n".join(logs.output))
+ self.assertEqual(await driver.chassis.request_interlock_state(), "tripped")
+ self.assertTrue(driver.interlock_tripped.is_set())
+ self.assertEqual(
+ zero_sequence(self.sent(driver, "chassis")[-2]),
+ zero_sequence(p.set_status_display("error").encode(1)),
+ )
+
+ async def test_skipping_configuration_leaves_unconfigured_pods_alone(self) -> None:
+ driver = await self.start(homed=False, configured=False)
+ await driver.initialize(skip_device_initialization=True)
+ self.assertEqual(self.written(driver), [])
+
+ async def test_a_skipped_pod_is_left_alone(self) -> None:
+ driver = await self.start_initialized(skip_right_x_arm=True)
+ self.assertEqual([n for n in self.names(driver, "span8") if not n.startswith("Get ")], [])
+ self.assertIn("Set State", self.names(driver, "multichannel"))
+
+ async def test_setup_brings_the_instrument_up_and_is_repeatable(self) -> None:
+ driver = generic_driver(generic_simulated_boards(homed=False))
+ self.addAsyncCleanup(driver.stop)
+ await driver.setup()
+ states = await driver.request_axis_states()
+ self.assertEqual({s for pod in states.values() for s in pod.values()}, {"enabled"})
+ await driver.setup() # configured already: not configured again
+ states = await driver.request_axis_states()
+ self.assertEqual({s for pod in states.values() for s in pod.values()}, {"enabled"})
+
+
+class PauseTests(SimulatedTest):
+ async def test_pause_trips_and_shows_paused_and_resume_re_arms(self) -> None:
+ driver = await self.start_initialized()
+ chassis_usb = self.usb(driver, "chassis")
+ self.mark(driver)
+ await driver.pause()
+ self.assertTrue(driver.paused)
+ self.assertFalse(chassis_usb.interlock.armed)
+ self.assertTrue(driver.interlock_tripped.is_set())
+ self.assertEqual(
+ [zero_sequence(m) for m in self.sent(driver, "chassis")],
+ [
+ zero_sequence(p.trip_interlock().encode(1)),
+ zero_sequence(p.set_status_display("paused").encode(1)),
+ ],
+ )
+ with self.assertRaisesRegex(RuntimeError, "already paused"):
+ await driver.pause()
+ await driver.resume()
+ self.assertFalse(driver.paused)
+ self.assertTrue(chassis_usb.interlock.armed)
+ self.assertFalse(driver.interlock_tripped.is_set())
+ states = await driver.request_axis_states()
+ self.assertEqual({s for pod in states.values() for s in pod.values()}, {"enabled"})
+
+ async def test_a_pause_is_not_an_error(self) -> None:
+ driver = await self.start_initialized()
+ with self.assertNoLogs(MASTER_LOGGER, "ERROR"):
+ await driver.pause()
+ await self.settle()
+
+ async def test_a_broken_light_curtain_keeps_it_paused(self) -> None:
+ driver = await self.start_initialized()
+ chassis_usb = self.usb(driver, "chassis")
+ await driver.pause()
+ chassis_usb.set_light_curtain(True)
+ with self.assertRaisesRegex(RuntimeError, "light curtain"):
+ await driver.resume()
+ self.assertTrue(driver.paused)
+ self.assertFalse(chassis_usb.interlock.armed)
+ chassis_usb.set_light_curtain(False)
+ await driver.resume()
+ self.assertFalse(driver.paused)
+ self.assertTrue(chassis_usb.interlock.armed)
+
+ async def test_pause_needs_an_armed_interlock(self) -> None:
+ driver = await self.start()
+ with self.assertRaisesRegex(RuntimeError, "not armed"):
+ await driver.pause()
+ with self.assertRaisesRegex(RuntimeError, "not paused"):
+ await driver.resume()
+
+
+class FaultAndStopTests(SimulatedTest):
+ async def test_a_motor_failing_on_its_own_trips_the_interlock(self) -> None:
+ driver = await self.start_initialized()
+ assert driver.left_x_arm is not None
+ x = driver.left_x_arm.axis("X")
+ self.mark(driver)
+ with self.assertLogs(MASTER_LOGGER, "ERROR") as logs:
+ # A Move All's NOTICE for X with a following error, sequence 0: nobody asked.
+ self.usb(driver, "multichannel")._queue(bytes([x.device, x.index, 0, 0, 0x50, 0xFE, 0x3C]))
+ await self.settle()
+ self.assertIn("The left X motor failed", "\n".join(logs.output))
+ self.assertEqual(self.names(driver, "chassis"), ["Trip Interlock", "Set Status Display"])
+ self.assertEqual(self.sent(driver, "chassis")[1][5:], p.set_status_display("error").params)
+ self.assertTrue(driver.interlock_tripped.is_set())
+
+ async def test_a_trip_the_driver_made_is_not_an_error(self) -> None:
+ driver = await self.start_initialized()
+ self.mark(driver)
+ with self.assertNoLogs(MASTER_LOGGER, "ERROR"):
+ await driver.stop()
+ # The chassis's own trip event, after the driver's trip.
+ self.usb(driver, "chassis")._queue(bytes([p.Device.INTERLOCK, 1, 0, 0, 0x10, 0x03, 0, 0xFF]))
+ await self.settle()
+
+ async def test_stop_leaves_the_instrument_at_rest(self) -> None:
+ driver = await self.start()
+ await driver.stop() # never armed: nothing is sent
+ self.assertEqual(self.written(driver), [])
+ driver = await self.start_initialized()
+ self.mark(driver)
+ await driver.stop()
+ for module in ("multichannel", "span8"):
+ self.assertEqual(self.names(driver, module), ["Stop Module Execution"])
+ self.assertEqual(
+ [zero_sequence(m) for m in self.sent(driver, "chassis")],
+ [
+ zero_sequence(p.trip_interlock().encode(1)),
+ zero_sequence(p.set_status_display("ready").encode(1)),
+ ],
+ )
+ self.assertFalse(self.usb(driver, "chassis").interlock.armed)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py
new file mode 100644
index 00000000000..57a539f3510
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py
@@ -0,0 +1,878 @@
+"""BiomekI7Driver: finds the instrument's ACE boards, works out what each one is, and owns them.
+
+A Biomek i7 shows up as one USB device per ACE module: the chassis, and one per arm. Which is which
+is not fixed by USB order or serial number, so setup opens every ACE device, asks each its module
+ID (its type, and an arm's side), and builds the chassis and a pod per arm from the answers. Only one
+program can hold an ACE board at a time: Biomek's Master Controller must not be running.
+
+At rest the interlock is tripped: the arms' drives have no motor power, and every CiA 402 drive
+reads FAULT. That is how the Master Controller leaves the instrument (its drive supply polls read
+off over 90% of the time), so it is not an error here. Bringing the instrument up arms the
+interlock and enables every axis, which is each faulted drive's reset, as Biomek does; a fault
+that does not clear stops it before anything moves. When anything fails once the interlock is
+armed, the driver shows ERROR and trips the interlock; `stop` trips it too, as the Master
+Controller's logs show it doing.
+"""
+
+import asyncio
+import logging
+from typing import (
+ Awaitable,
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Set,
+ Tuple,
+ Union,
+)
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import motion
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import (
+ ACE_PRODUCT_ID,
+ ACE_VENDOR_ID,
+ AceBoard,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import (
+ DeviceConfiguration,
+ ModuleConfiguration,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import INTERLOCK_TRIPPED_CODE, ace_error
+from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis
+from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door
+from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import MoveResult, Pod
+from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import XRail
+from pylabrobot.io.usb import USB
+
+logger = logging.getLogger(__name__)
+
+# A pod's drive supply ("+36V Interlock") reads about 35-36 V with the interlock armed and 0.1-0.16
+# V tripped (Master Controller polls, 2026-07 to 10). Above this it counts as on.
+DRIVE_SUPPLY_ON_VOLTS = 30.0
+
+# How long returning to rest may take, in seconds: two requests to the chassis.
+REST_TIMEOUT = 5.0
+
+
+async def _together(aws: Iterable[Awaitable[object]]) -> None:
+ """Run the pods' work at once. If one fails, the others are cancelled and waited for before the
+ error is raised, so nothing is left sending to a board behind the caller's back."""
+ tasks = [asyncio.ensure_future(a) for a in aws]
+ try:
+ await asyncio.gather(*tasks)
+ except BaseException:
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ raise
+
+
+def find_ace_boards() -> Dict[str, int]:
+ """Every ACE board attached: its USB serial number and current USB address.
+
+ Reading a serial number opens the device; the handle is released straight after, because a
+ WinUSB device admits one open handle at a time.
+ """
+ import usb.util # optional dependency, as in pylabrobot.io.usb
+
+ boards: Dict[str, int] = {}
+ for device in USB(ACE_VENDOR_ID, ACE_PRODUCT_ID, "ACE board").get_available_devices():
+ try:
+ boards[str(device.serial_number)] = device.address
+ finally:
+ usb.util.dispose_resources(device)
+ return boards
+
+
+class BiomekI7Driver:
+ """The Biomek i7's ACE boards, as a chassis and up to two pods."""
+
+ def __init__(
+ self,
+ serial_numbers: Optional[Sequence[str]] = None,
+ declared_configuration_json: Optional[str] = None,
+ boards: Optional[Sequence[AceBoard]] = None,
+ ):
+ """
+ Args:
+ serial_numbers: the ACE boards' USB serial numbers. Defaults to every ACE board attached.
+ declared_configuration_json: path of the instrument's declared configuration (motor tables,
+ and per pod its conversions, limits, geometry and calibration), as
+ `DeviceConfiguration.from_biomek` makes it from the instrument's Biomek files. Required:
+ the driver never falls back to another, the package's generic one included.
+ boards: boards to use instead of opening USB devices: a simulated instrument
+ (`simulator.simulated_boards`). With them, the checks that tie the configuration to a real
+ instrument (`discover`) are not made.
+
+ Raises:
+ ValueError: with no declared configuration, or one changed since it was imported
+ (`DeviceConfiguration.load`).
+ """
+ if declared_configuration_json is None:
+ raise ValueError(
+ "no declared configuration: pass `declared_configuration_json`, the instrument's own, made "
+ "by `DeviceConfiguration.from_biomek` from its Biomek files"
+ )
+ self._serial_numbers = list(serial_numbers) if serial_numbers is not None else None
+ self.declared_configuration_json = declared_configuration_json
+ self.declared = DeviceConfiguration.load(declared_configuration_json)
+ logger.info(
+ "declared configuration %s: chassis %s%s; %s",
+ declared_configuration_json,
+ self.declared.chassis_serial_number or "none",
+ " (generic)" if self.declared.generic else "",
+ "; ".join(
+ f"{name} {s.get('kind', '')} {s.get('path', '')} read {s.get('read_at', '?')} "
+ f"{s.get('fingerprint', '')[:19]}".replace(" ", " ")
+ for name, s in self.declared.sources.items()
+ ),
+ )
+ self.motor_tables = self.declared.motor_tables
+ # Called when a head's tips change; the device saves its heads' tips on it (`state_json`).
+ self.on_tips_changed: Callable[[], None] = lambda: None
+ self._given_boards = list(boards) if boards is not None else None
+ self.boards: List[AceBoard] = []
+ self._connected = False
+ self._armed = False # this driver armed the interlock, and has not tripped it since
+ self._tripping = False # this driver is tripping it: the chassis's trip event is our own
+ # While paused (`pause`): each pod's positions when the pause began, by side.
+ self._paused: Optional[Dict[str, Dict[str, int]]] = None
+ # Set while the interlock is tripped as far as this driver knows: from the start, when the
+ # chassis reports a trip, or when this driver trips it; cleared when it arms it.
+ self.interlock_tripped = asyncio.Event()
+ self.interlock_tripped.set()
+ self._unwatch: List[Callable[[], None]] = []
+ self._background: Set["asyncio.Task[None]"] = set()
+ self.chassis: Optional[Chassis] = None
+ # The shared X rail (design.md I7), built at discovery from the declared pod geometry.
+ self.rail: Optional[XRail] = None
+ # The pods, named as STAR names its X-arms: each fills an X-arm's slot (design.md, The pods).
+ self.left_x_arm: Optional[Pod] = None
+ self.right_x_arm: Optional[Pod] = None
+
+ # -- lifecycle -------------------------------------------------------------
+
+ async def setup(
+ self,
+ skip_device_initialization: bool = False,
+ *,
+ skip_left_x_arm: bool = False,
+ skip_right_x_arm: bool = False,
+ force_initialize: bool = False,
+ ) -> None:
+ """Connect to the instrument, find out what it is, and bring it up.
+
+ This moves the arms: every pod is homed. `discover` is the read-only part; with every skip
+ below set, setup only reads. Repeatable: the boards stay open, discovery reads them again, and
+ initializing an instrument that is up re-homes nothing (unless `force_initialize`). A setup that
+ fails part way releases the boards.
+
+ Args:
+ skip_device_initialization: do not load motor tables, even into a board that has lost them.
+ A pod with an axis not configured is then left as it is, and cannot move.
+ skip_left_x_arm: leave the left pod as it is: not configured, enabled or moved.
+ skip_right_x_arm: leave the right pod as it is.
+ force_initialize: home again axes that are already homed, as Biomek's Home All does.
+
+ Raises:
+ RuntimeError: if no chassis is found, two modules claim the same place, an axis reports a
+ fault, or a pod would move on the X rail beside a skipped pod whose X is not homed.
+ """
+ logger.warning(
+ "The Biomek i7 driver's discovery, configuration, interlock, Home All and moves have run on "
+ "one instrument; its commands were compared with Biomek's logs where Biomek ran the same "
+ "operation; it is untested on other instruments. Please report what works and what does "
+ "not."
+ )
+ if not self._connected:
+ await self._open()
+ try:
+ await self.discover()
+ await self.initialize(
+ skip_device_initialization=skip_device_initialization,
+ skip_left_x_arm=skip_left_x_arm,
+ skip_right_x_arm=skip_right_x_arm,
+ force_initialize=force_initialize,
+ )
+ except BaseException:
+ await self.stop()
+ raise
+
+ async def _open(self) -> None:
+ """Open every ACE board and start reading it."""
+ if self._given_boards is not None:
+ self.boards = list(self._given_boards)
+ else:
+ found = find_ace_boards()
+ if not found:
+ raise RuntimeError("no ACE boards (USB 0AB5:ACE0) found")
+ serials = self._serial_numbers or sorted(found)
+ missing = [s for s in serials if s not in found]
+ if missing:
+ raise RuntimeError(f"ACE boards {missing} not found; attached: {sorted(found)}")
+ # Opened by the address just enumerated: matching on serial number would open each device
+ # again to read its descriptor.
+ self.boards = [AceBoard(device_address=found[s], name=f"ACE {s}") for s in serials]
+ for board, serial in zip(self.boards, serials):
+ board.usb_serial_number = serial
+ self._connected = True
+ for board in self.boards:
+ await board.setup()
+
+ async def discover(self) -> None:
+ """Work out which board is which, then read each module, chassis first. Moves nothing, arms
+ nothing and writes nothing: it opens the boards if `setup` has not, and can be called on its
+ own.
+
+ Each board says what it is: Get Module ID answers a module type (`protocol.MODULE_TYPES`:
+ chassis, Multichannel, Span-8) and a side (left, right). That, not its USB serial number or
+ order, places it. Seen on one instrument; an unknown type or side, two boards claiming one
+ place, no chassis, or a pod type other than the declared one is refused (`_check_declared_against`).
+
+ On the instrument (no `boards` given), two checks follow, each refusing:
+ - the declared configuration must be this instrument's: its chassis serial number and each
+ declared pod's module serial number as the modules report them, and not the generic one
+ (`DeviceConfiguration.generic`);
+ - it must still match the Biomek files it was imported from, where they can be found
+ (`DeviceConfiguration.check_sources`): a re-framed deck or re-measured motors there make it
+ stale. Where they cannot be found (another computer), a warning says so.
+
+ Raises:
+ RuntimeError: for a board this driver cannot place, or no chassis.
+ ValueError: for a declared configuration that is not this instrument's, or is stale.
+ """
+ if not self._connected:
+ await self._open()
+ places: Dict[str, AceBoard] = {}
+ types: Dict[str, str] = {}
+ for board in self.boards:
+ module = p.parse_module_id((await board.send(p.get_module_id())).payload)
+ if module.type is None:
+ raise RuntimeError(
+ f"{board.name}: module type 0x{module.type_code:02X} is not one this driver knows"
+ )
+ place = "chassis" if module.type == "chassis" else str(module.side)
+ if place in places:
+ raise RuntimeError(
+ f"{board.name} and {places[place].name} both report themselves as {place}"
+ )
+ if place not in ("chassis", "left", "right"):
+ raise RuntimeError(
+ f"{board.name}: {module.type} module reports side 0x{module.side_code:02X}"
+ )
+ places[place] = board
+ types[place] = module.type
+ if "chassis" not in places:
+ raise RuntimeError("no chassis module among the ACE boards")
+ self._check_declared_against(types)
+ self.chassis = Chassis(places["chassis"])
+ self.left_x_arm = (
+ Pod(places["left"], "left", types["left"], self.motor_tables, self.declared.pods.get("left"))
+ if "left" in places
+ else None
+ )
+ self.right_x_arm = (
+ Pod(
+ places["right"], "right", types["right"], self.motor_tables, self.declared.pods.get("right")
+ )
+ if "right" in places
+ else None
+ )
+ self.rail = XRail({pod.side: pod.declared for pod in self.arms})
+ self._watch_faults()
+ for pod in self.arms:
+ pod.rail = self.rail
+ self.rail.readers[pod.side] = pod.request_rail_pose
+ modules: List[Tuple[str, ModuleConfiguration]] = [("chassis", await self.chassis.discover())]
+ for pod in self.arms:
+ modules.append((str(pod), await pod.discover()))
+ logger.info(
+ "found %s, module %s", pod, pod.configuration.serial_number if pod.configuration else "?"
+ )
+ for name, found in modules:
+ untested = found.untested_firmware()
+ if untested:
+ logger.warning(
+ "%s runs firmware this driver has not been run against: %s", name, "; ".join(untested)
+ )
+ if self._given_boards is not None:
+ return # simulated: no instrument to tie the configuration to
+ mismatches = self._serial_number_mismatches()
+ if mismatches:
+ raise ValueError(
+ "the declared configuration is not this instrument's: "
+ + "; ".join(mismatches)
+ + ". Its motor tables, conversions, geometry and calibration may not fit. Pass this "
+ "instrument's own `declared_configuration_json`, made by "
+ "`DeviceConfiguration.from_biomek` from its Biomek files."
+ )
+ sources = self.declared.check_sources()
+ if sources.changed:
+ shown = sources.changed[:20]
+ more = len(sources.changed) - len(shown)
+ raise ValueError(
+ "the declared configuration no longer matches the Biomek files it was imported from ("
+ + "; ".join(shown)
+ + (f"; and {more} more" if more else "")
+ + "): the instrument was re-calibrated or re-configured since. Import it again: "
+ "`DeviceConfiguration.from_biomek(...).save(path)`."
+ )
+ if sources.unavailable:
+ logger.warning(
+ "the declared configuration's sources cannot be read here (%s): whether the instrument "
+ "was re-calibrated since %s cannot be checked",
+ "; ".join(sources.unavailable),
+ self.declared.sources.get("instrument_file", {}).get("read_at", "it was imported"),
+ )
+ logger.info(
+ "the declared configuration is this instrument's: serial numbers match the modules; "
+ "sources %s",
+ "unchanged since import" if not sources.unavailable else "partly not checked (above)",
+ )
+
+ async def request_serial_numbers(self) -> Dict[str, Optional[str]]:
+ """The serial numbers the modules report: `chassis`, and `left` / `right` for each pod found.
+ Moves nothing.
+
+ Raises:
+ RuntimeError: before discovery (`discover` or `setup`).
+ """
+ return self._serial_numbers_found()
+
+ def _serial_number_mismatches(self) -> List[str]:
+ """How the declared configuration's serial numbers differ from the modules' (read at discovery),
+ each as a sentence; empty when they are this instrument's."""
+ found = self._serial_numbers_found()
+ d = self.declared
+ problems = (
+ ["it is the generic configuration, which describes no instrument"] if d.generic else []
+ )
+ if d.chassis_serial_number != found["chassis"]:
+ problems.append(
+ f"chassis {d.chassis_serial_number or 'not recorded'}, found {found['chassis']}"
+ )
+ for side, pod in d.pods.items():
+ if side in found and pod.module_serial_number != found[side]:
+ problems.append(
+ f"{side} pod module {pod.module_serial_number or 'not recorded'}, found {found[side]}"
+ )
+ return problems
+
+ def _check_declared_against(self, types: Dict[str, str]) -> None:
+ """Refuse an instrument whose pods are not the ones declared: their motor tables and geometry
+ would be another arm's. A pod declared but not found, or found but not declared, is only
+ logged (a single-pod instrument, or one being configured).
+
+ Raises:
+ ValueError: if a pod is declared on a side where the boards report another arm type.
+ """
+ for side in ("left", "right"):
+ declared = self.declared.pods.get(side)
+ found = types.get(side)
+ if declared is not None and found is not None and declared.module_type != found:
+ raise ValueError(
+ f"the declared configuration has a {declared.module_type} pod on the {side}, but the "
+ f"boards report a {found}; pass this instrument's own `declared_configuration_json`"
+ )
+ if (declared is None) != (found is None):
+ logger.warning(
+ "%s pod: declared %s, found %s",
+ side,
+ declared.module_type if declared else "nothing",
+ found or "nothing",
+ )
+
+ def save_configuration(self, path: str, indent: Optional[int] = 2) -> None:
+ """Write the declared configuration to `path`, as loaded, for `declared_configuration_json` to
+ read back. A configuration is made only from the instrument's Biomek files
+ (`DeviceConfiguration.from_biomek`), so nothing found at discovery is written into it.
+
+ Args:
+ path: where to write it.
+ indent: how far to indent the JSON, or None to write it on one line.
+ """
+ self.declared.save(path, indent=indent)
+
+ def _serial_numbers_found(self) -> Dict[str, Optional[str]]:
+ if self.chassis is None or self.chassis.configuration is None:
+ raise RuntimeError("the modules have not been read; call `discover()` or `setup()` first")
+ found: Dict[str, Optional[str]] = {"chassis": self.chassis.configuration.serial_number}
+ for pod in self.arms:
+ found[pod.side] = pod.configuration.serial_number if pod.configuration else None
+ return found
+
+ async def stop(self) -> None:
+ """Return the instrument to rest and release every board. Moves nothing.
+
+ If this driver armed the interlock, as the Master Controller does when its host goes away: each
+ pod's module is stopped (Stop Module Execution) and its positions forgotten, then the
+ interlock is tripped and READY shown. Otherwise nothing is written. What the boards do on their
+ own when the host goes away is not known.
+ """
+ # As the Master Controller does when its host goes away: stop each pod's
+ # module, forget its positions, then trip the interlock. Only while this driver has the
+ # interlock armed: otherwise the drives have no power, and a read-only session writes nothing.
+ if self._armed:
+ for pod in self.arms:
+ try:
+ await asyncio.wait_for(pod._unchecked_fw_stop_module_execution(), REST_TIMEOUT)
+ except BaseException:
+ logger.exception("could not stop %s", pod)
+ pod._forget_positions()
+ await self._return_to_rest()
+ for unwatch in self._unwatch:
+ unwatch()
+ self._unwatch = []
+ for board in self.boards:
+ try:
+ await board.stop()
+ except Exception:
+ logger.exception("failed to release %s", board.name)
+ self._connected = False
+
+ # -- what the instrument has ------------------------------------------------
+
+ @property
+ def arms(self) -> List[Pod]:
+ """The pods this instrument has, left first (STAR's `arms`)."""
+ return [pod for pod in (self.left_x_arm, self.right_x_arm) if pod is not None]
+
+ @property
+ def x_arm(self) -> Pod:
+ """The pod, on an instrument with one (STAR's `x_arm`).
+
+ Raises:
+ RuntimeError: before discovery, when which pods are fitted is not yet known.
+ ValueError: with no pod, or two; reach two as `left_x_arm` and `right_x_arm`.
+ """
+ if self.chassis is None:
+ raise RuntimeError("the instrument has not been read; call `discover()` or `setup()` first")
+ arms = self.arms
+ if not arms:
+ raise ValueError("this instrument has no pod")
+ if len(arms) > 1:
+ raise ValueError(
+ "this instrument has two pods, so `x_arm` is ambiguous - reach it through "
+ "`left_x_arm` or `right_x_arm`."
+ )
+ return arms[0]
+
+ def arm(self, name: Union[str, int]) -> Pod:
+ """A pod by any name it goes by: its side (`"left"`), Biomek's number (`1`, `"Pod1"`), or
+ Biomek's component name in its logs (`"MC_1"`). For porting Biomek methods and logs, which
+ name pods by number; the driver itself names them by side.
+
+ Raises:
+ KeyError: if no pod goes by that name.
+ """
+ for pod in self.arms:
+ if name in (pod.side, pod.pod_number, f"Pod{pod.pod_number}", pod.component):
+ return pod
+ raise KeyError(f"no pod {name!r}; have {[(p.side, p.component) for p in self.arms]}")
+
+ @property
+ def front_cover(self) -> Optional[Door]:
+ """The door, by STAR's name for it, once discovery has found the chassis."""
+ return None if self.chassis is None else self.chassis.front_cover
+
+ async def request_axis_states(self) -> Dict[str, Dict[str, p.AxisStateName]]:
+ """Every axis's state, by pod side then axis name. Moves nothing."""
+ return {pod.side: await pod.request_axis_states() for pod in self.arms}
+
+ # -- configuration, interlock and homing ---------------------------------------
+ # These write to the boards and move the arms. Run them only on a clear deck, with someone at
+ # the emergency stop.
+
+ def _require_chassis(self) -> Chassis:
+ if self.chassis is None:
+ raise RuntimeError("no chassis; call `setup()` first")
+ return self.chassis
+
+ def skipped_sides(
+ self, *, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False
+ ) -> Set[str]:
+ """The sides (`"left"`, `"right"`) a setup with these skips leaves as they are."""
+ return {s for s, skip in (("left", skip_left_x_arm), ("right", skip_right_x_arm)) if skip}
+
+ async def initialize(
+ self,
+ skip_device_initialization: bool = False,
+ *,
+ skip_left_x_arm: bool = False,
+ skip_right_x_arm: bool = False,
+ force_initialize: bool = False,
+ ) -> None:
+ """Bring the instrument up: what `setup` does after discovery, and what Home All is later.
+
+ Reads every axis's state first. A pod with an axis not configured (the board was powered up, or
+ a drive lost its parameters) has its motor tables loaded; one fully configured does not, since
+ loading them again would un-home it. Then the pods are homed together (`home`). The arguments
+ are those of `setup`.
+
+ An axis in fault is not refused: enabling it is its fault reset, as when Biomek re-arms and
+ enables after a fault, and calling this is the person's go-ahead that Biomek waits for. A CiA
+ 402 drive in fault with its motor supply off is the instrument at rest and is only noted; any
+ other fault is warned about, since under power it usually means a following error or a
+ collision. A fault that does not clear fails the enable, and `home` returns the instrument to
+ rest before anything moves.
+
+ Raises:
+ RuntimeError: if a pod would move on the X rail beside a skipped pod whose X is not homed
+ (nothing has been written), or the drive supply does not come up when armed.
+ AceError: if an axis cannot be enabled, or a move or home fails; the interlock is then
+ tripped and ERROR shown.
+ """
+ skipped = self.skipped_sides(skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm)
+ pods = [pod for pod in self.arms if pod.side not in skipped]
+ if skip_device_initialization and not pods:
+ return
+
+ states = await self.request_axis_states()
+ for pod in pods:
+ faulted = [name for name, state in states[pod.side].items() if state == "fault"]
+ if not faulted:
+ continue
+ supply = await pod.request_drive_supply()
+ at_rest = supply < DRIVE_SUPPLY_ON_VOLTS and all(
+ pod.axis(name).drive == "cia402" for name in faulted
+ )
+ if at_rest:
+ logger.info("%s: %s in fault with the drive supply off (%.1f V), as at rest", pod,
+ ", ".join(faulted), supply) # fmt: skip
+ else:
+ positions = await pod.request_positions()
+ logger.warning(
+ "%s: %s in fault with the drive supply at %.1f V; enabling will reset them. A fault under "
+ "power usually means a following error or a collision: check the deck. Positions: %s",
+ pod,
+ ", ".join(faulted),
+ supply,
+ {name: positions[name] for name in faulted},
+ )
+
+ unconfigured = [pod for pod in pods if "not_configured" in states[pod.side].values()]
+ if unconfigured and skip_device_initialization:
+ logger.warning(
+ "%s not configured, and configuring was skipped; left as they are, and they cannot move",
+ ", ".join(str(pod) for pod in unconfigured),
+ )
+ pods = [pod for pod in pods if pod not in unconfigured]
+ unconfigured = []
+ if pods:
+ await self._check_shared_x_rail(pods)
+ if unconfigured:
+ await self.configure(unconfigured)
+ if pods:
+ await self.home(pods, force=force_initialize)
+
+ # A pod that answered every request is not a pod that came up, so each is asked again.
+ states = await self.request_axis_states()
+ down = [
+ f"{pod.side} {name} ({state})"
+ for pod in pods
+ for name, state in states[pod.side].items()
+ if state != "enabled"
+ ]
+ if down:
+ logger.warning("initialize finished with these axes not enabled: %s", ", ".join(down))
+
+ async def _check_shared_x_rail(self, moving: Sequence[Pod]) -> None:
+ """Refuse to move pods on the X rail beside a pod left out whose X is not homed: where that pod
+ stands is not known. Reads only.
+
+ Raises:
+ RuntimeError: if a pod left out has its X not homed.
+ """
+ for pod in self.arms:
+ if pod in moving:
+ continue
+ others = ", ".join(str(m) for m in moving)
+ if await pod.request_homed_state("X") != "homed":
+ raise RuntimeError(
+ f"the {pod} is left as it is and its X is not homed, so where it stands on the shared X "
+ f"rail is not known; the {others} cannot move beside it. Bring up both pods. Nothing was "
+ "moved"
+ )
+ logger.warning(
+ "the %s is left as it is; the %s's X moves are not checked against it", pod, others
+ )
+
+ async def configure(self, pods: Optional[Sequence[Pod]] = None) -> None:
+ """Load the motor tables into pods' boards (every pod by default), as after a power-up. Moves
+ nothing.
+
+ A board keeps its tables until it loses power. Loading them into a configured board is
+ accepted, and leaves every axis disabled and not homed, so this un-homes
+ the pods; `initialize` loads them only where an axis is not configured.
+ """
+ chassis = self._require_chassis()
+ await chassis.prepare_interlock()
+ for pod in self.arms if pods is None else pods:
+ await pod.configure()
+ await chassis._io_box_write_after_configure()
+
+ async def arm_interlock(self, pods: Optional[Sequence[Pod]] = None) -> None:
+ """Arm the interlock, check the pods' drive supply came up, then enable every axis of pods
+ (every pod by default). Enabling resets a drive's fault. Moves nothing: the drives hold where
+ they stand.
+
+ The door does not take part: Biomek arms with it open, and opening it does not trip the
+ interlock (Biomek's logs); only its state is logged.
+
+ Raises:
+ RuntimeError: if the interlock does not arm (the light curtain broken), or a pod's drive
+ supply stays off.
+ AceError: if an axis cannot be enabled.
+ """
+ targets = self.arms if pods is None else list(pods)
+ chassis = self._require_chassis()
+ if await chassis.front_cover.request_state() == "open":
+ logger.info("arming the interlock with the door open (the door does not trip it)")
+ self._armed = True # before the request: a re-arm that times out may still have armed it
+ self.interlock_tripped.clear()
+ await chassis.arm_interlock()
+ state = await chassis.request_interlock_state()
+ if state != "armed":
+ raise RuntimeError(f"the interlock reads {state} after re-arming")
+ for pod in targets:
+ supply = await pod.request_drive_supply()
+ if supply < DRIVE_SUPPLY_ON_VOLTS:
+ raise RuntimeError(f"{pod}: the drive supply reads {supply:.1f} V with the interlock armed")
+ await _together(pod.enable_axes() for pod in targets)
+
+ async def home(self, pods: Optional[Sequence[Pod]] = None, force: bool = False) -> None:
+ """Home pods (every pod by default) at once, the Master Controller's Home All without its
+ Span-8 priming.
+
+ Arms the interlock, then homes the pods together, as Biomek does: each runs its `HM` recipe.
+ Needs the motor tables loaded (`initialize` sees to it).
+
+ If anything fails once the interlock is armed, ERROR is shown and the interlock tripped, which
+ cuts the drives' power, before the error is raised; nothing is retried. Biomek instead leaves
+ the drives powered while its dialog waits for the person; here no one may be waiting, so the
+ instrument goes back to rest.
+
+ Args:
+ pods: the pods to home.
+ force: home again axes already homed, as Biomek does. Without it they are only moved to
+ where a Home leaves them.
+ """
+ targets = self.arms if pods is None else list(pods)
+
+ try:
+ await self.arm_interlock(targets)
+ await _together(pod.home(force=force) for pod in targets)
+ except BaseException:
+ await self._return_to_rest(error=True)
+ raise
+
+ async def move_axes(
+ self, targets: Mapping[str, Mapping[str, int]], speed: int = 1000
+ ) -> Dict[str, MoveResult]:
+ """Move axes of both pods at once: each pod's `AM` (`Pod.move_axes`), started together, as
+ Biomek runs the two pods' steps. The shared X rail keeps them apart: a move into the other
+ pod's range is refused, and one crossing only the other's path waits for it.
+
+ Args:
+ targets: per pod side (`left`, `right`), its axes' targets in counts.
+ speed: 1..1000, Biomek's speed field, for both.
+
+ Returns:
+ Each pod's result, by side.
+
+ Raises:
+ ValueError: for a side with no pod. Otherwise as `Pod.move_axes`; if one pod's move fails,
+ the other's is cancelled and waited for first. Nothing returns the instrument to rest:
+ whether to is the caller's (design.md I5).
+ """
+ pods: Dict[str, Pod] = {pod.side: pod for pod in self.arms}
+ missing = sorted(set(targets) - set(pods))
+ if missing:
+ raise ValueError(f"no pod on the {', '.join(missing)}; have {sorted(pods)}")
+ results: Dict[str, MoveResult] = {}
+
+ async def move(side: str) -> None:
+ results[side] = await pods[side].move_axes(targets[side], speed)
+
+ await _together(move(side) for side in targets)
+ return results
+
+ async def _return_to_rest(self, error: bool = False) -> None:
+ """Trip the interlock, if this driver armed it, and show READY (ERROR with `error`). Never
+ raises: it runs on the way out of a failure."""
+ if not self._armed:
+ return
+ await self._trip(error)
+
+ async def _trip(self, error: bool) -> None:
+ """Trip the interlock and show READY or ERROR. Never raises."""
+ if self.chassis is None:
+ return
+ self._tripping = True
+ try:
+ await asyncio.wait_for(self.chassis.trip_interlock(error=error), REST_TIMEOUT)
+ self._armed = False
+ self.interlock_tripped.set()
+ except BaseException:
+ logger.exception(
+ "could not trip the interlock; the drives may still be powered: use the E-stop"
+ )
+ finally:
+ self._tripping = False
+
+ # -- pause for access --------------------------------------------------------------
+ # Biomek's whole-system pause, as its logs show it: a deliberate interlock trip with PAUSED shown
+ # and the pods' positions saved; resuming re-arms, enables every axis and moves the pods back.
+ # There is no mute: the light curtain may be broken only because the drives have no power.
+
+ @property
+ def paused(self) -> bool:
+ """Whether the instrument is paused (`pause`), waiting for `resume`."""
+ return self._paused is not None
+
+ async def pause(self) -> None:
+ """Pause for access: cut the pods' drive power and show PAUSED, so the light curtain may be
+ broken without an error. Call it between operations, as Biomek's Pause step runs between
+ steps: a move still running is stopped where it is. Moving the pods out of the way first is
+ the caller's. Each pod's positions are read and kept for `resume`.
+
+ Raises:
+ RuntimeError: if the interlock is not armed by this driver (nothing to pause), or the
+ instrument is already paused.
+ """
+ if self._paused is not None:
+ raise RuntimeError("the instrument is already paused")
+ if not self._armed:
+ raise RuntimeError("the interlock is not armed: nothing to pause")
+ chassis = self._require_chassis()
+ self._tripping = True
+ try:
+ await chassis._unchecked_fw_trip_interlock()
+ self._armed = False
+ self.interlock_tripped.set()
+ finally:
+ self._tripping = False
+ await chassis._unchecked_fw_set_status_display("paused")
+ # Biomek reads the positions after the trip; the drives answer without power. Kept as the
+ # adjusted positions moves take (a Span-8 Z channel's hysteresis), as the driver keeps them.
+ saved: Dict[str, Dict[str, int]] = {}
+ for pod in self.arms:
+ read = await pod.request_positions()
+ saved[pod.side] = {
+ name: motion.update_cpos(pod.cpositions[name], counts, pod.axis(name).hysteresis)[1]
+ for name, counts in read.items()
+ }
+ pod._forget_positions()
+ self._paused = saved
+ logger.info("paused: the interlock is tripped; the light curtain may be broken")
+
+ async def resume(self, speed: int = 200) -> None:
+ """Resume after `pause`: re-arm the interlock, enable every axis, then move each pod back to
+ where it was when paused (an axis pushed by hand is returned; the plunger and syringe pumps
+ are not, as Biomek does not, nor is a gripper holding labware opened or closed). Nothing is
+ homed.
+
+ Args:
+ speed: 1..1000, Biomek's speed field, for the moves back.
+
+ Raises:
+ RuntimeError: if not paused, or if the interlock does not arm (the light curtain still
+ broken): the instrument stays paused, so clear it and call `resume` again.
+ """
+ saved = self._paused
+ if saved is None:
+ raise RuntimeError("the instrument is not paused")
+ try:
+ await self.arm_interlock()
+ except BaseException:
+ self._armed = False
+ self.interlock_tripped.set()
+ raise
+ self._paused = None
+ logger.info("resumed: the interlock is armed")
+ for pod in self.arms:
+ keep = {"D"} | ({"GG"} if pod._held_labware is not None else set())
+ back = {
+ name: counts
+ for name, counts in saved.get(pod.side, {}).items()
+ if name not in keep and not pod.axis(name).is_pump
+ }
+ if any(pod.cpositions[name][1] != counts for name, counts in back.items()):
+ logger.info("%s moving back to where it was paused", pod.component)
+ await pod.move_axes(back, speed)
+
+ # -- faults the boards report unasked ------------------------------------------
+ # As the Master Controller handles them, as its logs show it.
+
+ def _watch_faults(self) -> None:
+ """Listen for the chassis reporting the interlock tripped and the pods reporting a motor that
+ failed on its own (both arrive unasked, sequence 0)."""
+ for unwatch in self._unwatch:
+ unwatch()
+ self._unwatch = []
+ if self.chassis is not None:
+ self._unwatch.append(self.chassis.board.subscribe(self._on_chassis_message))
+ for pod in self.arms:
+ self._unwatch.append(pod.board.subscribe(self._pod_watcher(pod)))
+
+ def _pod_watcher(self, pod: Pod) -> Callable[[p.Reply], None]:
+ return lambda reply: self._on_pod_message(pod, reply)
+
+ def _on_chassis_message(self, reply: p.Reply) -> None:
+ """The interlock tripped (Notify On Interlock Trip): the light curtain broken, or a trip by
+ the host."""
+ if reply.status == p.Status.EVENT and (reply.device, reply.opcode) == p.INTERLOCK_TRIPPED:
+ self._interlock_tripped("A light curtain violation has occurred.")
+
+ def _on_pod_message(self, pod: Pod, reply: p.Reply) -> None:
+ """A motor's Move All ended in an error nobody was waiting for: the Master Controller trips
+ the interlock with "The motor failed: ." (an interlock trip itself is
+ reported by the chassis instead)."""
+ if not (
+ reply.opcode == 0x50
+ and reply.status == p.Status.NOTICE
+ and reply.device in (p.Device.MOTOR, p.Device.PUMP)
+ and reply.error_code is not None
+ and reply.error_code != INTERLOCK_TRIPPED_CODE
+ ):
+ return
+ names = {(a.device, a.index): a.name for a in pod.axes}
+ axis = names.get((reply.device, reply.index), f"device 0x{reply.device:02X} {reply.index}")
+ error = ace_error(reply.error_code, reply.device_error, f"{pod} {axis}")
+ logger.error("The %s %s motor failed: %s.", pod.side, axis, error)
+ self.interlock_tripped.set()
+ for each in self.arms:
+ each._forget_positions()
+ self._in_background(self._trip(error=True))
+
+ def _interlock_tripped(self, reason: str) -> None:
+ """What the Master Controller does when the interlock trips under a running instrument: every
+ position is forgotten (read again after re-arming), waits end, and ERROR is shown. A trip this
+ driver made itself (at rest, or after a failure) only marks it tripped."""
+ ours = self._tripping or not self._armed
+ self.interlock_tripped.set()
+ for pod in self.arms:
+ pod._forget_positions()
+ if ours:
+ return
+ logger.error("the interlock tripped: %s", reason)
+ self._armed = False
+ if self.chassis is not None:
+ self._in_background(self.chassis._unchecked_fw_set_status_display("error"))
+
+ def _in_background(self, coroutine: Awaitable[None]) -> None:
+ """Run a board write from a message handler, which cannot wait; its failure is logged."""
+
+ async def run() -> None:
+ try:
+ await coroutine
+ except Exception:
+ logger.exception("after a fault the boards reported")
+
+ task = asyncio.get_running_loop().create_task(run())
+ self._background.add(task)
+ task.add_done_callback(self._background.discard)
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master_tests.py
new file mode 100644
index 00000000000..2df0cea1da8
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master_tests.py
@@ -0,0 +1,218 @@
+"""Discovery on a replayed instrument: each board placed by what it says it is, then read."""
+
+import asyncio
+import itertools
+import unittest
+from typing import Any, Dict, List
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard
+from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis
+from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import (
+ generic_boards,
+ generic_driver,
+ generic_recording,
+)
+
+# The commands that only read: discovery sends nothing else.
+READS = {name for name in p.COMMANDS.values() if name.startswith(("Get ", "Read ", "List "))}
+
+
+def answer(recording: Dict[str, Any], module: str, key: str, reply: str) -> None:
+ """Have `module` answer the request `key` (its bytes less the sequence) with `reply`."""
+ entries: List[List[Any]] = recording["boards"][module]
+ for entry in entries:
+ if entry[0] == key:
+ entry[1] = [reply]
+ return
+ entries.append([key, [reply]])
+
+
+def module_id(recording: Dict[str, Any], module: str, type_code: int, side_code: int) -> None:
+ answer(recording, module, "00000000", f"00000000000200{type_code:02X}{side_code:02X}")
+
+
+class ReplayedTestCase(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self) -> None:
+ asyncio.get_running_loop().set_debug(False) # the test loop's debug mode makes replays slow
+
+
+class PlacementTests(ReplayedTestCase):
+ async def test_boards_are_placed_by_what_they_say_in_any_order(self) -> None:
+ for order in itertools.permutations(["chassis", "multichannel", "span8"]):
+ with self.subTest(order=order):
+ driver = generic_driver(generic_boards(modules=order))
+ await driver.discover()
+ try:
+ self.assertIsNotNone(driver.chassis)
+ assert driver.chassis is not None and driver.left_x_arm and driver.right_x_arm
+ self.assertEqual(driver.chassis.board.name, "replayed chassis")
+ self.assertEqual(driver.left_x_arm.board.name, "replayed multichannel")
+ self.assertEqual(driver.right_x_arm.board.name, "replayed span8")
+ finally:
+ await driver.stop()
+ left, right = driver.left_x_arm, driver.right_x_arm
+ assert left is not None and right is not None
+ self.assertEqual(str(left), "left pod (Pod1, multichannel)")
+ self.assertEqual((left.component, left.pod_number), ("MC_1", 1))
+ self.assertEqual((right.component, right.pod_number), ("SPAN8_2", 2))
+ self.assertEqual(driver.arms, [left, right])
+
+ async def test_two_boards_in_one_place_are_refused(self) -> None:
+ recording = generic_recording()
+ module_id(recording, "span8", 0xFB, 0x01) # a second left pod
+ driver = generic_driver(generic_boards(recording))
+ with self.assertRaisesRegex(RuntimeError, "replayed span8 and replayed multichannel both"):
+ await driver.discover()
+ await driver.stop()
+
+ async def test_no_chassis_is_refused(self) -> None:
+ driver = generic_driver(generic_boards(modules=["multichannel", "span8"]))
+ with self.assertRaisesRegex(RuntimeError, "no chassis"):
+ await driver.discover()
+ await driver.stop()
+
+ async def test_an_unknown_module_type_is_refused(self) -> None:
+ recording = generic_recording()
+ module_id(recording, "span8", 0x42, 0x02)
+ driver = generic_driver(generic_boards(recording))
+ with self.assertRaisesRegex(RuntimeError, "module type 0x42"):
+ await driver.discover()
+ await driver.stop()
+
+ async def test_an_unknown_side_is_refused(self) -> None:
+ recording = generic_recording()
+ module_id(recording, "span8", 0xFB, 0x07)
+ driver = generic_driver(generic_boards(recording))
+ with self.assertRaisesRegex(RuntimeError, "side 0x07"):
+ await driver.discover()
+ await driver.stop()
+
+ async def test_setup_releases_the_boards_when_discovery_fails(self) -> None:
+ boards = generic_boards(modules=["multichannel", "span8"])
+ with self.assertRaisesRegex(RuntimeError, "no chassis"):
+ await generic_driver(boards).setup()
+ self.assertFalse(any(board.connected for board in boards))
+
+
+class PodNameTests(ReplayedTestCase):
+ async def test_one_pod(self) -> None:
+ driver = generic_driver(generic_boards(modules=["chassis", "span8"]))
+ with self.assertRaisesRegex(RuntimeError, "discover"):
+ driver.x_arm
+ await driver.discover()
+ self.assertIsNone(driver.left_x_arm)
+ self.assertIs(driver.x_arm, driver.right_x_arm)
+ await driver.stop()
+
+ async def test_two_pods(self) -> None:
+ driver = generic_driver()
+ await driver.discover()
+ with self.assertRaisesRegex(ValueError, "left_x_arm"):
+ driver.x_arm
+ for name in ("left", 1, "Pod1", "MC_1"):
+ self.assertIs(driver.arm(name), driver.left_x_arm)
+ for name in ("right", 2, "Pod2", "SPAN8_2"):
+ self.assertIs(driver.arm(name), driver.right_x_arm)
+ with self.assertRaises(KeyError):
+ driver.arm("MC_2")
+ await driver.stop()
+
+
+class ReadTests(ReplayedTestCase):
+ async def asyncSetUp(self) -> None:
+ await super().asyncSetUp()
+ self.boards = generic_boards()
+ self.driver = generic_driver(self.boards)
+
+ async def asyncTearDown(self) -> None:
+ await self.driver.stop()
+
+ async def test_discovery_on_its_own_opens_the_boards_and_only_reads(self) -> None:
+ await self.driver.discover()
+ self.assertTrue(all(board.connected for board in self.boards))
+ for board in self.boards:
+ assert isinstance(board.io, ReplayAceUSB)
+ self.assertEqual(board.io.unanswered, [], board.name)
+ sent = {p.COMMANDS[(m[0], m[4])] for m in board.io.requests}
+ self.assertLessEqual(sent, READS, board.name)
+
+ async def test_serial_numbers(self) -> None:
+ with self.assertRaisesRegex(RuntimeError, "discover"):
+ await self.driver.request_serial_numbers()
+ await self.driver.discover()
+ serials = await self.driver.request_serial_numbers()
+ self.assertEqual(set(serials), {"chassis", "left", "right"})
+ for serial in serials.values():
+ assert serial is not None
+ self.assertTrue(serial.startswith("SIMULATED"), serial)
+ self.assertEqual(len(set(serials.values())), 3)
+
+ async def test_each_modules_boards_and_inputs(self) -> None:
+ await self.driver.discover()
+ chassis, left, right = self.driver.chassis, self.driver.left_x_arm, self.driver.right_x_arm
+ assert chassis and chassis.configuration and left and left.configuration
+ assert right and right.configuration
+ self.assertEqual(chassis.configuration.module_id.type, "chassis")
+ self.assertEqual(chassis.configuration.digital_inputs[1], "Door Sensor")
+ self.assertEqual(chassis.configuration.analog_units[9], "deg. C")
+ self.assertEqual(
+ [b.index for b in left.configuration.boards],
+ list(range(len(left.configuration.boards), 0, -1)), # highest index first
+ )
+ self.assertTrue(any(b.hardware.name == "AccuFrame" for b in left.configuration.boards))
+ self.assertEqual(right.configuration.untested_firmware(), [])
+
+ async def test_sensor_reads(self) -> None:
+ await self.driver.discover()
+ chassis, left, right = self.driver.chassis, self.driver.left_x_arm, self.driver.right_x_arm
+ assert chassis and left and right
+ analog = await chassis.request_analog_inputs()
+ self.assertIn("Temperature", analog)
+ self.assertEqual(set(await chassis.request_digital_inputs()), {"Door Sensor"})
+ self.assertEqual(len(await chassis.request_digital_outputs()), 1)
+ self.assertIsInstance(await chassis.request_legacy_alp_devices(), list)
+ for pod in (left, right):
+ # The recording answers as the instrument did when it was made, with the interlock armed.
+ self.assertGreater(await pod.request_drive_supply(), 30.0)
+ self.assertIn("+36V Interlock", await pod.request_analog_inputs())
+ self.assertEqual(len(await left.request_accuframe_offsets()), 3)
+
+ async def test_untested_firmware_is_warned_about(self) -> None:
+ with self.assertNoLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "WARNING"):
+ await self.driver.discover()
+ recording = generic_recording()
+ answer(recording, "span8", "00000012", "000000001202" + "00EFBEADDE")
+ driver = generic_driver(generic_boards(recording))
+ with self.assertLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "WARNING") as logs:
+ await driver.discover()
+ await driver.stop()
+ self.assertIn("module image CRC 0xdeadbeef", "\n".join(logs.output))
+
+ async def test_stop_releases_the_boards_and_discovery_runs_again(self) -> None:
+ await self.driver.discover()
+ await self.driver.stop()
+ self.assertFalse(any(board.connected for board in self.boards))
+ await self.driver.discover()
+ self.assertTrue(all(board.connected for board in self.boards))
+
+
+class InterlockStateTests(unittest.IsolatedAsyncioTestCase):
+ """Get Interlock Status, which the Master Controller never sends, answers the interlock's byte
+ (read on the instrument 2026-11-09: `FF` tripped, `00` armed)."""
+
+ async def test_states(self) -> None:
+ for byte, state in (("FF", "tripped"), ("00", "armed")):
+ board = AceBoard(
+ io=ReplayAceUSB({"01010010": ["0101000010" + "0200" + byte]}), default_timeout=0.3
+ )
+ await board.setup()
+ try:
+ self.assertEqual(await Chassis(board).request_interlock_state(), state)
+ finally:
+ await board.stop()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/module.py b/pylabrobot/beckman_coulter/biomek_i7/driver/module.py
new file mode 100644
index 00000000000..3956e87bfd8
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/module.py
@@ -0,0 +1,72 @@
+"""Reading what an ACE module says about itself: identity, its boards, and its inputs.
+
+The order follows the Master Controller's cold start: the module, then each of its boards from
+the highest index down (a motion board's serial number and firmware image, any other board's
+application version), then the names of its inputs and outputs. Nothing here moves or writes.
+"""
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import BoardInfo, ModuleConfiguration
+
+# Board kinds whose identity is a serial number and firmware image; every other kind reports an
+# application version. AccuFrame boards are left at their hardware version.
+_IMAGE_BOARDS = {0x00}
+_ACCUFRAME = 0xE3
+
+
+async def read_module(board: AceBoard) -> ModuleConfiguration:
+ """Read a module's identity, board inventory and input/output names."""
+ module_id = p.parse_module_id((await board.send(p.get_module_id())).payload)
+ hardware = p.parse_hardware_version((await board.send(p.get_module_hardware_version())).payload)
+ serial = p.parse_string((await board.send(p.get_module_serial_number())).payload)
+ crc = p.parse_u32((await board.send(p.get_module_application_image_crc())).payload)
+ length = p.parse_u32((await board.send(p.get_module_application_image_length())).payload)
+ counts = p.parse_device_count((await board.send(p.get_module_device_count())).payload)
+ usb_serial = board.usb_serial_number
+ config = ModuleConfiguration(module_id, usb_serial, serial, hardware, crc, length, counts)
+
+ for index in range(counts.get(p.Device.BOARD, 0), 0, -1):
+ info = BoardInfo(
+ index,
+ p.parse_hardware_version((await board.send(p.get_board_hardware_version(index))).payload),
+ )
+ if info.hardware.type_code in _IMAGE_BOARDS:
+ info.serial_number = p.parse_string(
+ (await board.send(p.get_board_serial_number(index))).payload
+ )
+ info.application_crc = p.parse_u32(
+ (await board.send(p.get_board_application_image_crc(index))).payload
+ )
+ info.application_length = p.parse_u32(
+ (await board.send(p.get_board_application_image_length(index))).payload
+ )
+ elif info.hardware.type_code != _ACCUFRAME:
+ info.application_version = p.parse_string(
+ (await board.send(p.get_board_application_version(index))).payload
+ )
+ config.boards.append(info)
+
+ io_counts = p.parse_device_count((await board.send(p.get_io_service_device_count())).payload)
+ for index in range(1, io_counts.get(p.Device.ANALOG_INPUT, 0) + 1):
+ name = await board.send(p.get_input_output_name(p.Device.ANALOG_INPUT, index))
+ units = await board.send(p.get_analog_input_units(index))
+ config.analog_inputs[index] = p.parse_string(name.payload)
+ config.analog_units[index] = p.parse_string(units.payload)
+ for index in range(1, io_counts.get(p.Device.DIGITAL_INPUT, 0) + 1):
+ name = await board.send(p.get_input_output_name(p.Device.DIGITAL_INPUT, index))
+ config.digital_inputs[index] = p.parse_string(name.payload)
+ for index in range(1, io_counts.get(p.Device.DIGITAL_OUTPUT, 0) + 1):
+ name = await board.send(p.get_input_output_name(p.Device.DIGITAL_OUTPUT, index))
+ config.digital_outputs[index] = p.parse_string(name.payload)
+ return config
+
+
+async def read_analog_inputs(board: AceBoard, config: ModuleConfiguration) -> dict:
+ """Every analog input's value, by name, in its units."""
+ replies = await board.send_many(
+ [p.read_input_output(p.Device.ANALOG_INPUT, i) for i in config.analog_inputs]
+ )
+ return {
+ config.analog_inputs[i]: p.parse_float(r.payload) for i, r in zip(config.analog_inputs, replies)
+ }
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/motion.py b/pylabrobot/beckman_coulter/biomek_i7/driver/motion.py
new file mode 100644
index 00000000000..5161162969a
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/motion.py
@@ -0,0 +1,395 @@
+"""Biomek's coordinated-move model: how the Master Controller turns one `AM` into each axis's move.
+
+Pure arithmetic, no board access. It reproduces the requests the Master Controller sends for
+each `AM`. Per `AM`:
+
+1. Each axis's distance comes from where the Master Controller last put it, not from a position
+ read: per axis it keeps `(position, adjusted)` (`cpositions`), the position it last commanded
+ and the one it targets for hysteresis. `adjust_delta` adds an axis's hysteresis (only the Span-8
+ Z channels have any) to moves in one direction; `update_cpos` keeps the pair afterwards.
+2. `get_scaling_factors`: per axis, velocity, acceleration and jerk per count of travel, the
+ slowest axis winning: `max(min limit, speed/1000 x max limit) / distance`. Axes are grouped:
+ each Span-8 channel's pump (D1-D8) and its Z, while that pump moves, have their own group, so
+ eight channels aspirating different volumes each finish together with their own Z; everything
+ else is one group, scaled by the slowest axis anywhere.
+3. `get_motions_and_duration`: each axis's velocity/acceleration/jerk is its factor x its distance,
+ rounded and clamped to its limits; jerk is then corrected (`correct_j`) so the S-curve's phases
+ land on the board's 2.5 kHz servo ticks; pumps are rounded to their own steps. The move takes the
+ longest axis's time (`motor_move_time`, from the uncorrected jerk), rounded up to the ms.
+4. The Move All carries that duration + 5000 ms as its timeout.
+
+Integer division is exact (`Fraction`) until something inexact (a float) enters, so results match
+the Master Controller's logged requests to the last count.
+"""
+
+import math
+from dataclasses import dataclass
+from fractions import Fraction
+from typing import Dict, List, Mapping, Optional, Sequence, Tuple, TypeVar, Union
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis
+
+Number = Union[int, Fraction, float]
+CPos = Tuple[Optional[int], int]
+"""An axis's `(position, adjusted)`: the position last commanded (None when unknown, as after a
+force-limited move), and the position its next move is planned from."""
+
+MOVE_ALL_MARGIN_MS = 5000
+"""Added to the planned duration for the Move All's timeout, as logged."""
+
+PARTITIONED = {f"D{n}": n for n in range(1, 9)}
+PARTITIONED_Z = {f"Z{n}": n for n in range(1, 9)}
+
+
+@dataclass(frozen=True)
+class Motion:
+ """One axis's move in a coordinated move, in counts; `jerk` None for an axis that
+ takes none (trapezoidal profile, pumps)."""
+
+ axis: str
+ position: int
+ velocity: int
+ acceleration: int
+ jerk: Optional[int]
+
+
+# -- exact arithmetic ----------------------------------------------------------------------------
+
+
+def _inexact(*xs: Number) -> bool:
+ return any(isinstance(x, float) for x in xs)
+
+
+def _min(*xs: Number) -> Number:
+ m = min(xs)
+ return float(m) if _inexact(*xs) else m
+
+
+def _max(*xs: Number) -> Number:
+ m = max(xs)
+ return float(m) if _inexact(*xs) else m
+
+
+def _div(x: Number, *ys: Number) -> Number:
+ """`/`, exact when every argument is."""
+ for y in ys:
+ x = x / y if _inexact(x, y) else Fraction(x) / Fraction(y)
+ return x
+
+
+def _sqrt(x: Number) -> Number:
+ """`sqrt`, exact for an exact perfect square, inexact otherwise."""
+ if not isinstance(x, float):
+ f = Fraction(x)
+ if f >= 0:
+ n, d = math.isqrt(f.numerator), math.isqrt(f.denominator)
+ if n * n == f.numerator and d * d == f.denominator:
+ return Fraction(n, d)
+ return math.sqrt(float(x))
+
+
+def _cbrt(x: Number) -> float:
+ """x ** 0.3333333333333333, as the Master Controller computes the cube root."""
+ return math.pow(float(x), 0.3333333333333333)
+
+
+def _exact_round(x: Number) -> int:
+ """x rounded half to even, as Python's `round`."""
+ return round(x)
+
+
+def range_(lo: Number, x: Number, hi: Number) -> Number:
+ """x clamped to [lo, hi]."""
+ return lo if x < lo else (x if x < hi else hi)
+
+
+def quantize(x: Number, width: float) -> int:
+ """x to the nearest multiple of width."""
+ return int(round(_div(x, width)) * width)
+
+
+# -- move times ------------------------------------------------------------------------------------
+
+
+def _s_curve_phases(d: Number, v_max: Number, a_max: Number, j: Number) -> Tuple[Number, Number]:
+ t1a = _min(_sqrt(_div(v_max, j)), _cbrt(_div(d, 2, j)))
+ t1b = _div(a_max, j)
+ if t1a < t1b:
+ return t1a, t1a
+ x = _div(a_max, 2, j)
+ return t1b, _min(_div(v_max, a_max), _sqrt(x * x + _div(d, a_max)) - x)
+
+
+def s_curve_move_time(d: Number, v_max: Number, a_max: Number, j: Number) -> Number:
+ """Seconds for an S-curve move of d counts."""
+ if d > 0 and v_max > 0 and a_max > 0 and j > 0:
+ t1, t2 = _s_curve_phases(d, v_max, a_max, j)
+ return _div(d, j, t1, t2) + t1 + t2
+ if d == 0:
+ return 0
+ raise ValueError(f"s_curve_move_time: invalid input {d} {v_max} {a_max} {j}")
+
+
+def trapezoid_move_time(d: Number, v_max: Number, a: Number) -> Number:
+ """Seconds for a trapezoidal move of d counts."""
+ if d > 0 and v_max > 0 and a > 0:
+ t1a, t1b = _div(v_max, a), _sqrt(_div(d, a))
+ return t1a + _div(d, v_max) if t1a < t1b else t1b * 2
+ if d == 0:
+ return 0
+ raise ValueError(f"trapezoid_move_time: invalid input {d} {v_max} {a}")
+
+
+def trapezoid_a_for_s_curve(d: Number, v_max: Number, a_max: Number, j: Number) -> Number:
+ """The acceleration a trapezoidal move needs to take as long as the
+ S-curve one (so an axis without jerk keeps pace with ones that have it)."""
+ if not (d > 0 and v_max > 0 and a_max > 0 and j > 0):
+ raise ValueError(f"trapezoid_a_for_s_curve: invalid input {d} {v_max} {a_max} {j}")
+ t1, t2 = _s_curve_phases(d, v_max, a_max, j)
+ return _div(j * t1 * t2, t1 + t2)
+
+
+def motor_move_time(d: Number, v: Number, a: Number, j: Optional[Number]) -> Number:
+ """Seconds for a motor's move."""
+ return s_curve_move_time(d, v, a, j) if j else trapezoid_move_time(d, v, a)
+
+
+def pump_move_time(d: Number, v_max: Number, a: Number, s: Number, c: Number) -> Number:
+ """Seconds for a syringe pump move of d counts, starting at velocity s and
+ ending at cutoff velocity c."""
+ if d > 0 and v_max > 0 and a > 0:
+ s = _min(s, v_max)
+ c = _max(s, _min(c, v_max))
+ tmp1 = s * s + 2 * a * d
+ if tmp1 < c * c:
+ return _div(_sqrt(tmp1) - s, a)
+ tmp2 = _div(s * s + c * c, 2)
+ p = _min(_sqrt(a * d + tmp2), v_max)
+ return _div(d, p) + _div(p - s - c + _div(tmp2, p), a)
+ if d == 0:
+ return 0
+ raise ValueError(f"pump_move_time: invalid input {d} {v_max} {a} {s} {c}")
+
+
+# -- coordination (the Master Controller's coordinated move) -------------------------------------
+
+
+def correct_j(d: int, v_max: int, a_max: int, j: int, jmin: int, jmax: int) -> int:
+ """The jerk sent, adjusted so the S-curve's jerk phase (t1) and, when it reaches its
+ maximum acceleration, its acceleration phase (t2) are whole 0.4 ms servo ticks."""
+
+ def q(x: Number) -> float:
+ return round(float(x) * 2500.0) * (1 / 2500.0)
+
+ def correct(t1: float, t2: float) -> int:
+ if t1 > 0.0 and t2 > 0.0:
+ return int(range_(jmin, _exact_round(v_max / (t1 * t2)), jmax))
+ return j
+
+ t1a = _div(a_max, j)
+ t1b = _sqrt(_div(v_max, j))
+ t1c = _cbrt(_div(d, 2, j))
+ if t1a <= t1b and t1a <= t1c:
+ t2a = _div(v_max, a_max)
+ x = _div(t1a, 2)
+ t2b = _sqrt(x * x + _div(d, a_max)) - x
+ return correct(q(t1a), q(t2a)) if t2a < t2b else j
+ if t1b < t1a and t1b < t1c:
+ t1 = q(t1b)
+ return correct(t1, t1)
+ return j
+
+
+def _partition(axes: Sequence[Axis], deltas: Sequence[int], i: int) -> int:
+ name = axes[i].name
+ if name in PARTITIONED:
+ return PARTITIONED[name]
+ if name in PARTITIONED_Z:
+ n = PARTITIONED_Z[name]
+ for k, a in enumerate(axes):
+ if a.name == f"D{n}":
+ return 0 if deltas[k] == 0 else n
+ return 0
+
+
+def get_scaling_factors(
+ axes: Sequence[Axis], deltas: Sequence[int], fspeed: float
+) -> List[Optional[List[Number]]]:
+ """Per moving axis, its group's [velocity, acceleration, jerk] per count
+ of travel (None for an axis that does not move). Group 0's factors end as the minimum over every
+ group; each other group's as the minimum of its own and group 0's (as it was before that)."""
+ factors: List[List[Number]] = [[math.inf, math.inf, math.inf] for _ in range(9)]
+ out: List[Optional[List[Number]]] = []
+ for i, (axis, delta) in enumerate(zip(axes, deltas)):
+ if delta == 0:
+ out.append(None)
+ continue
+ d = abs(delta)
+ lim = axis.limits
+ f = factors[_partition(axes, deltas, i)]
+ f[0] = _min(_div(_max(lim.min_velocity, fspeed * lim.max_velocity), d), f[0])
+ f[1] = _min(_div(_max(lim.min_acceleration, fspeed * lim.max_acceleration), d), f[1])
+ if lim.max_jerk:
+ f[2] = _min(_div(_max(lim.min_jerk, fspeed * lim.max_jerk), d), f[2])
+ out.append(f)
+ f0 = factors[0]
+ for fi in factors[1:]:
+ for k in range(3):
+ fi[k] = _min(f0[k], fi[k])
+ for fi in factors[1:]:
+ for k in range(3):
+ f0[k] = _min(f0[k], fi[k])
+ return out
+
+
+def get_motions_and_duration(
+ axes: Sequence[Axis],
+ cpositions: Sequence[CPos],
+ deltas: Sequence[int],
+ fspeed: float,
+ cutoff_velocity: int = 0,
+) -> Tuple[List[Motion], int]:
+ """Each moving axis's motion, and the move's duration in ms (the slowest
+ axis's, rounded up). `cutoff_velocity` is the Span-8 pumps' (0 on a Multichannel)."""
+ scaling = get_scaling_factors(axes, deltas, fspeed)
+ motions: List[Motion] = []
+ duration: Number = 0
+ for i, (axis, cpos, delta) in enumerate(zip(axes, cpositions, deltas)):
+ if delta == 0:
+ continue
+ d = abs(delta)
+ factor = scaling[i]
+ assert factor is not None
+ k_v, k_a, k_j = factor
+ lim = axis.limits
+
+ def cvt(k: Number) -> int:
+ return _exact_round(k * d)
+
+ velocity = int(range_(lim.min_velocity, cvt(k_v), lim.max_velocity))
+ k_acc = k_a if lim.max_jerk or math.isinf(k_j) else trapezoid_a_for_s_curve(1, k_v, k_a, k_j)
+ acceleration = int(range_(lim.min_acceleration, cvt(k_acc), lim.max_acceleration))
+ jerk = int(range_(lim.min_jerk, cvt(k_j), lim.max_jerk)) if lim.max_jerk else None
+ if cpos[0] is None:
+ raise ValueError(f"{axis.name}: position unknown; read it before planning a move")
+ position = delta + cpos[0]
+ if axis.is_pump:
+ pump = axis.pump_limits
+ s = pump.min_start_velocity
+ velocity, acceleration = quantize(velocity, 4.0), quantize(acceleration, 10000.0)
+ if delta > 0 and pump.backlash > 0:
+ t = pump_move_time(d + pump.backlash, velocity, acceleration, s, s) + pump_move_time(
+ pump.backlash, velocity, acceleration, s, cutoff_velocity
+ )
+ else:
+ t = pump_move_time(d, velocity, acceleration, s, cutoff_velocity)
+ motions.append(Motion(axis.name, position, velocity, acceleration, None))
+ else:
+ sent = (
+ correct_j(d, velocity, acceleration, jerk, lim.min_jerk, lim.max_jerk)
+ if jerk is not None
+ else None
+ )
+ t = motor_move_time(d, velocity, acceleration, jerk)
+ motions.append(Motion(axis.name, position, velocity, acceleration, sent))
+ duration = _max(duration, t)
+ return motions, math.ceil(1000 * duration)
+
+
+# -- positions and hysteresis ----------------------------------------------------------------------
+
+
+def adjust_delta(cpos: CPos, delta: int, hysteresis: int) -> int:
+ """The distance an axis travels for a move of `delta` from its adjusted position,
+ with its hysteresis added when moving in hysteresis's direction (negative hysteresis: downward
+ moves)."""
+ if hysteresis == 0 or delta == 0:
+ return delta
+ if cpos[0] is None:
+ raise ValueError("position unknown; read it before planning a move")
+ offset = cpos[1] - cpos[0]
+ if hysteresis < 0:
+ return delta + offset + hysteresis if delta < 0 else delta + offset
+ return delta + offset if delta < 0 else delta + offset + hysteresis
+
+
+def update_cpos(cpos: CPos, position: int, hysteresis: int) -> CPos:
+ """An axis's `(position, adjusted)` once it is at `position`."""
+ if hysteresis == 0:
+ return position, position
+ adjusted = cpos[1]
+ if hysteresis < 0:
+ if position < adjusted + hysteresis:
+ return position, position - hysteresis
+ return (position, adjusted) if position <= adjusted else (position, position)
+ if position < adjusted:
+ return position, position
+ return (
+ (position, adjusted) if position <= adjusted + hysteresis else (position, position - hysteresis)
+ )
+
+
+T = TypeVar("T")
+
+
+def spawn_order(motions: Sequence[T]) -> List[T]:
+ """The order the Master Controller's per-axis requests of one move reach the board: the motions
+ reversed, taken two at a time from the end, each pair in order. Motions 1..5 go out as 1, 3 2,
+ 5 4. Matches every multi-axis move logged."""
+ reverse = list(reversed(motions))
+ pairs = [reverse[i : i + 2] for i in range(0, len(reverse), 2)]
+ return [m for pair in reversed(pairs) for m in pair]
+
+
+def span_targets(
+ cpositions: Mapping[str, CPos], y: Optional[int] = None, span: Optional[int] = None
+) -> Dict[str, int]:
+ """The Span-8 channels' Y targets for a move given Biomek's `Y` (channel 1) and `S` (the span from
+ channel 1 to 8), in counts, as the Master Controller's logged moves place them.
+ An omitted `y` is channel 1's adjusted position, an omitted `span` the current span
+ (max(Y8 - Y1, 0), adjusted); channel i goes to y + round((i - 1) * span / 7), an exact ratio
+ rounded half to even.
+
+ Raises:
+ ValueError: for a negative span.
+ """
+ y1, y8 = cpositions["Y1"][1], cpositions["Y8"][1]
+ y = y1 if y is None else y
+ span = max(y8 - y1, 0) if span is None else span
+ if span < 0:
+ raise ValueError(f"span {span} is negative")
+ return {f"Y{i}": y + round(Fraction((i - 1) * span, 7)) for i in range(1, 9)}
+
+
+def plan_move(
+ axes: Sequence[Axis],
+ cpositions: Mapping[str, CPos],
+ targets: Mapping[str, int],
+ speed: int = 1000,
+ cutoff_velocity: int = 0,
+) -> Tuple[List[Motion], int, Dict[str, CPos]]:
+ """An absolute coordinated move, as the Master Controller plans an `AM`: each target is
+ where the axis's adjusted position should end. Returns the motions (axes already there are left
+ out), the Move All timeout in ms (duration + 5000), and every axis's `(position, adjusted)`
+ after the move.
+
+ Raises:
+ ValueError: for a speed outside 1..1000 or an unknown axis.
+ """
+ if not 1 <= speed <= 1000:
+ raise ValueError(f"speed {speed} is outside 1..1000")
+ names = {a.name for a in axes}
+ unknown = set(targets) - names
+ if unknown:
+ raise ValueError(f"no axes named {sorted(unknown)}; have {sorted(names)}")
+ cpos = [cpositions[a.name] for a in axes]
+ deltas = [
+ adjust_delta(c, targets[a.name] - c[1], a.hysteresis) if a.name in targets else 0
+ for a, c in zip(axes, cpos)
+ ]
+ motions, duration = get_motions_and_duration(axes, cpos, deltas, speed / 1000.0, cutoff_velocity)
+ after = dict(cpositions)
+ for m in motions:
+ axis = next(a for a in axes if a.name == m.axis)
+ after[m.axis] = update_cpos(cpositions[m.axis], m.position, axis.hysteresis)
+ return motions, duration + MOVE_ALL_MARGIN_MS, after
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/motion_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/motion_tests.py
new file mode 100644
index 00000000000..2b670a9133f
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/motion_tests.py
@@ -0,0 +1,329 @@
+"""Biomek's coordinated-move model, checked against coordinated moves Biomek made.
+
+`LOGGED_MOVES` holds logged `AM` commands, one of each kind, each with the positions the Master
+Controller planned it from, and the Set Move Parameters and Move All timeout it sent.
+"""
+
+import math
+import unittest
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import motion
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration
+
+TABLES = generic_configuration().motor_tables
+
+LOGGED_MOVES = [
+ {
+ "cpositions": {
+ "GR": [-175443, -175443],
+ "GY": [63763, 63763],
+ "GZ": [-159, -159],
+ "X": [35841, 35841],
+ "Y": [37266, 37266],
+ "Z": [0, 0],
+ },
+ "cutoff_velocity": 0,
+ "kind": "multichannel full axes=0",
+ "module": "multichannel",
+ "motions": {},
+ "speed": 1000,
+ "targets": {"GR": -175443, "GY": 63763, "GZ": -159, "X": 35841, "Y": 37266, "Z": 0},
+ "timeout": 5000,
+ },
+ {
+ "cpositions": {"GR": [-175774, -175774], "GZ": [-161, -161]},
+ "cutoff_velocity": 0,
+ "kind": "span8 full axes=0",
+ "module": "span8",
+ "motions": {},
+ "speed": 1000,
+ "targets": {"GR": -175774, "GZ": -161},
+ "timeout": 5000,
+ },
+ {
+ "cpositions": {"GG": [0, 0]},
+ "cutoff_velocity": 0,
+ "kind": "multichannel slow axes=0",
+ "module": "multichannel",
+ "motions": {},
+ "speed": 200,
+ "targets": {"GG": 0},
+ "timeout": 5000,
+ },
+ {
+ "cpositions": {
+ "D": [91463, 91463],
+ "GG": [0, 0],
+ "GR": [-175443, -175443],
+ "GY": [63730, 63730],
+ "GZ": [-160, -160],
+ "X": [4833, 4833],
+ "Y": [10952, 10952],
+ "Z": [0, 0],
+ },
+ "cutoff_velocity": 0,
+ "kind": "multichannel full jerk-corrected s-curve trapezoid axes=3",
+ "module": "multichannel",
+ "motions": {
+ "D": {"acceleration": 1228495, "position": 43176, "velocity": 196608},
+ "X": {"acceleration": 51, "jerk": 1280000, "position": 4831, "velocity": 8},
+ "Y": {"acceleration": 25, "jerk": 640000, "position": 10953, "velocity": 4},
+ },
+ "speed": 1000,
+ "targets": {
+ "D": 43176,
+ "GG": 0,
+ "GR": -175443,
+ "GY": 63730,
+ "GZ": -160,
+ "X": 4831,
+ "Y": 10953,
+ "Z": 0,
+ },
+ "timeout": 5411,
+ },
+ {
+ "cpositions": {"D3": [1320, 1320], "Z3": [-78827, -78827]},
+ "cutoff_velocity": 3600,
+ "kind": "span8 slow hysteresis jerk-corrected pump axes=2",
+ "module": "span8",
+ "motions": {
+ "D3": {"acceleration": 10000, "position": 720, "velocity": 604},
+ "Z3": {"acceleration": 4000, "jerk": 21792949, "position": -78587, "velocity": 488},
+ },
+ "speed": 26,
+ "targets": {"D3": 720, "Z3": -78587},
+ "timeout": 6007,
+ },
+ {
+ "cpositions": {"Z": [-255, -255]},
+ "cutoff_velocity": 0,
+ "kind": "multichannel full jerk-corrected s-curve axes=1",
+ "module": "multichannel",
+ "motions": {
+ "Z": {"acceleration": 128000, "jerk": 698690, "position": -31982, "velocity": 24320}
+ },
+ "speed": 1000,
+ "targets": {"Z": -31982},
+ "timeout": 6678,
+ },
+ {
+ "cpositions": {
+ "Y1": [203370, 203370],
+ "Y2": [203370, 203370],
+ "Y3": [203370, 203370],
+ "Y4": [203370, 203370],
+ "Y5": [203370, 203370],
+ "Y6": [203370, 203370],
+ "Y7": [203370, 203370],
+ "Y8": [203370, 203370],
+ },
+ "cutoff_velocity": 0,
+ "kind": "span8 full axes=0 span-y",
+ "module": "span8",
+ "motions": {},
+ "speed": 1000,
+ "targets": {
+ "Y1": 203370,
+ "Y2": 203370,
+ "Y3": 203370,
+ "Y4": 203370,
+ "Y5": 203370,
+ "Y6": 203370,
+ "Y7": 203370,
+ "Y8": 203370,
+ },
+ "timeout": 5000,
+ },
+ {
+ "cpositions": {
+ "D": [43161, 43161],
+ "GG": [34983, 34983],
+ "GR": [-175443, -175443],
+ "GY": [63747, 63747],
+ "GZ": [-796, -796],
+ "X": [35692, 35692],
+ "Y": [37274, 37274],
+ "Z": [0, 0],
+ },
+ "cutoff_velocity": 0,
+ "kind": "multichannel full jerk-corrected s-curve axes=4",
+ "module": "multichannel",
+ "motions": {
+ "GG": {"acceleration": 100, "jerk": 546, "position": 34981, "velocity": 19},
+ "GR": {"acceleration": 50, "jerk": 273, "position": -175442, "velocity": 9},
+ "X": {"acceleration": 50, "jerk": 273, "position": 35691, "velocity": 9},
+ "Z": {"acceleration": 128000, "jerk": 698880, "position": -2561, "velocity": 24320},
+ },
+ "speed": 1000,
+ "targets": {
+ "D": 43161,
+ "GG": 34981,
+ "GR": -175442,
+ "GY": 63747,
+ "GZ": -796,
+ "X": 35691,
+ "Y": 37274,
+ "Z": -2561,
+ },
+ "timeout": 5490,
+ },
+ {
+ "cpositions": {
+ "GR": [-175443, -175443],
+ "GY": [63744, 63744],
+ "GZ": [-796, -796],
+ "X": [35767, 35767],
+ "Y": [37244, 37244],
+ "Z": [0, 0],
+ },
+ "cutoff_velocity": 0,
+ "kind": "multichannel full axes=0",
+ "module": "multichannel",
+ "motions": {},
+ "speed": 1000,
+ "targets": {"GR": -175443, "GY": 63744, "GZ": -796, "X": 35767, "Y": 37244, "Z": 0},
+ "timeout": 5000,
+ },
+]
+
+
+def load_moves():
+ return LOGGED_MOVES
+
+
+class LoggedMoveTests(unittest.TestCase):
+ """Every logged move plans to exactly what the Master Controller sent."""
+
+ def test_every_logged_move(self) -> None:
+ moves = load_moves()
+ for move in moves:
+ axes = TABLES.axes(move["module"])
+ cpositions = {a.name: (0, 0) for a in axes}
+ cpositions.update({n: (c[0], c[1]) for n, c in move["cpositions"].items()})
+ motions, timeout, _ = motion.plan_move(
+ axes, cpositions, move["targets"], move["speed"], move["cutoff_velocity"]
+ )
+ planned = {
+ m.axis: {
+ "position": m.position,
+ "velocity": m.velocity,
+ "acceleration": m.acceleration,
+ **(
+ {"jerk": m.jerk if m.jerk is not None else 0}
+ if "jerk" in move["motions"].get(m.axis, {})
+ else {}
+ ),
+ } # fmt: skip
+ for m in motions
+ }
+ with self.subTest(kind=move["kind"], targets=move["targets"]):
+ self.assertEqual(planned, move["motions"])
+ if motions:
+ self.assertEqual(timeout, move["timeout"])
+
+ def test_fixture_covers_every_kind_of_move(self) -> None:
+ kinds = " ".join(m["kind"] for m in load_moves())
+ # Hysteresis is measured per instrument and the generic configuration has none: it is
+ # checked on its own (`HysteresisTests`), and the logged moves with it in the local replay.
+ for kind in ("multichannel", "span8", "slow", "trapezoid", "pump", "jerk-corrected",
+ "span-y", "axes=4", "axes=0"): # fmt: skip
+ self.assertIn(kind, kinds)
+
+
+class MoveTimeTests(unittest.TestCase):
+ def test_short_s_curve_never_reaches_max_acceleration(self) -> None:
+ # 280 counts of the Multichannel Z at its limits: pure jerk, 4 phases of (d / 2j)^(1/3).
+ t = motion.s_curve_move_time(280, 24320, 128000, 698880)
+ self.assertAlmostEqual(t, 4 * (280 / 2 / 698880) ** (1 / 3), places=12)
+ self.assertEqual(math.ceil(1000 * t), 235)
+
+ def test_trapezoid(self) -> None:
+ self.assertEqual(motion.trapezoid_move_time(200, 10, 1), 30) # reaches v: v/a + d/v
+ self.assertEqual(motion.trapezoid_move_time(4, 10, 1), 4) # triangle: 2 sqrt(d/a), exact
+
+ def test_zero_distance_takes_no_time(self) -> None:
+ self.assertEqual(motion.s_curve_move_time(0, 1, 1, 1), 0)
+ self.assertEqual(motion.pump_move_time(0, 1, 1, 1, 1), 0)
+
+ def test_invalid_input_raises(self) -> None:
+ with self.assertRaises(ValueError):
+ motion.s_curve_move_time(10, 0, 1, 1)
+
+
+class HysteresisTests(unittest.TestCase):
+ """The Span-8 Z channels' hysteresis is negative: downward moves travel |h| further, and the
+ adjusted position stays |h| above where the axis is."""
+
+ H = -862
+
+ def test_down_move_adds_hysteresis(self) -> None:
+ cpos = (1000, 1000)
+ self.assertEqual(motion.adjust_delta(cpos, -500, self.H), -500 - 862)
+
+ def test_up_move_after_down_move_does_not(self) -> None:
+ cpos = motion.update_cpos((1000, 1000), -362, self.H)
+ self.assertEqual(cpos, (-362, 500))
+ self.assertEqual(motion.adjust_delta(cpos, 1000 - cpos[1], self.H), 1000 - 500 + 862)
+
+ def test_no_hysteresis_leaves_moves_alone(self) -> None:
+ self.assertEqual(motion.adjust_delta((5, 5), 10, 0), 10)
+ self.assertEqual(motion.update_cpos((5, 5), 15, 0), (15, 15))
+
+
+class PlanTests(unittest.TestCase):
+ AXES = TABLES.axes("multichannel")
+
+ def cpositions(self, **at: int):
+ out = {a.name: (0, 0) for a in self.AXES}
+ out.update({n: (p, p) for n, p in at.items()})
+ return out
+
+ def test_axes_already_there_are_left_out(self) -> None:
+ motions, timeout, after = motion.plan_move(self.AXES, self.cpositions(X=100), {"X": 100})
+ self.assertEqual(motions, [])
+ self.assertEqual(timeout, motion.MOVE_ALL_MARGIN_MS)
+ self.assertEqual(after["X"], (100, 100))
+
+ def test_leader_moves_at_its_limits_and_followers_arrive_with_it(self) -> None:
+ motions, _, after = motion.plan_move(self.AXES, self.cpositions(), {"X": 100000, "Y": 1000})
+ x, y = motions
+ lim = self.AXES[0].limits
+ self.assertEqual(
+ (x.axis, x.velocity, x.acceleration), ("X", lim.max_velocity, lim.max_acceleration)
+ )
+ self.assertEqual(y.velocity, round(lim.max_velocity * 1000 / 100000))
+ self.assertEqual(after["Y"], (1000, 1000))
+
+ def test_speed_scales_the_leader(self) -> None:
+ (x,), _, _ = motion.plan_move(self.AXES, self.cpositions(), {"X": 100000}, speed=500)
+ self.assertEqual(x.velocity, round(self.AXES[0].limits.max_velocity * 0.5))
+
+ def test_rejects_bad_speed_and_unknown_axes(self) -> None:
+ with self.assertRaises(ValueError):
+ motion.plan_move(self.AXES, self.cpositions(), {"X": 1}, speed=0)
+ with self.assertRaises(ValueError):
+ motion.plan_move(self.AXES, self.cpositions(), {"Q": 1})
+
+ def test_unknown_position_must_be_read_first(self) -> None:
+ cpositions = self.cpositions()
+ cpositions["X"] = (None, 0)
+ with self.assertRaises(ValueError):
+ motion.plan_move(self.AXES, cpositions, {"X": 1000})
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
+class SpawnOrderTests(unittest.TestCase):
+ def test_pairs_from_the_end_each_in_order(self) -> None:
+ # As logged: a Multichannel Z+D move sends D first; a Span-8 move of X and Z1-Z8 sends X, then
+ # Z2 Z1, Z4 Z3, ...
+ self.assertEqual(motion.spawn_order(["Z", "D"]), ["D", "Z"])
+ z = [f"Z{n}" for n in range(1, 9)]
+ self.assertEqual(
+ motion.spawn_order(["X"] + z), ["X", "Z2", "Z1", "Z4", "Z3", "Z6", "Z5", "Z8", "Z7"]
+ )
+ self.assertEqual(motion.spawn_order(["X"]), ["X"])
+ self.assertEqual(motion.spawn_order([]), [])
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/motors.py b/pylabrobot/beckman_coulter/biomek_i7/driver/motors.py
new file mode 100644
index 00000000000..0f09f7e49b9
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/motors.py
@@ -0,0 +1,166 @@
+"""Motor tables: the axes each arm's board drives, and the Configure parameters each one takes.
+
+A board does not keep its motor tables across a power cycle and cannot be asked for them, so the
+host loads them at a cold start. Two more values per axis never reach a board: the Master
+Controller keeps them in its own motor record and applies them itself. `home_position` is its
+`phome`: where its Home All leaves X, the Multichannel's Y and the gripper axes (see
+`driver/recipes/homing.py`; the Z channels, the plunger and the Span-8 Y channels end elsewhere).
+`hysteresis` is what it adds to an axis's targets; only the Span-8 Z channels have any, and it
+differs channel by channel, measured per instrument. They are data, the Master Controller's own
+record of the instrument (the `modules` section of its declared configuration,
+`driver/configuration.py`), not something the driver works out. No instrument's tables ship with
+the driver: they come with each instrument's declared configuration.
+
+Three layouts of Configure parameters were seen, each starting with the axis's limits:
+
+ CiA 402 drive (X, Y, Z, D, grippers): 0x00 | 6 x u32 velocity/acceleration/jerk limits |
+ s32 min position | s32 max position | ...
+ SAGIAN drive (Span-8 Y1-Y8, Z1-Z8): 0xFF | the same limits | ...
+ syringe pump (Span-8 D1-D8): 8 x u32 velocity/acceleration limits |
+ s32 min position | s32 max position | u16 backlash
+"""
+
+import struct
+from dataclasses import dataclass
+from typing import Any, Dict, List, Literal, Optional
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import Device
+
+ModuleType = Literal["multichannel", "span8"]
+
+
+@dataclass(frozen=True)
+class AxisLimits:
+ """An axis's limits, as the Master Controller's motor record has them (`vmin` .. `jmax`). A
+ `max_jerk` of 0 means the axis takes no jerk (a trapezoidal profile: the Multichannel D and the
+ gripper Z, and the syringe pumps)."""
+
+ min_position: int
+ max_position: int
+ max_velocity: int
+ max_acceleration: int
+ max_jerk: int
+ min_velocity: int = 1
+ min_acceleration: int = 1
+ min_jerk: int = 0
+
+
+@dataclass(frozen=True)
+class PumpLimits:
+ """A syringe pump's own parameters (the Master Controller's ``), velocities in
+ counts/s and `backlash` in counts."""
+
+ min_start_velocity: int
+ max_start_velocity: int
+ min_cutoff_velocity: int
+ max_cutoff_velocity: int
+ backlash: int
+
+
+@dataclass(frozen=True)
+class Axis:
+ """One axis an arm's board drives, in the board's counts."""
+
+ name: str
+ device: int
+ index: int
+ configure: bytes
+ home_position: int = 0
+ hysteresis: int = 0
+
+ @property
+ def is_pump(self) -> bool:
+ return self.device == Device.PUMP
+
+ @property
+ def drive(self) -> Literal["cia402", "sagian", "pump"]:
+ """The kind of drive, read off the Configure layout. A CiA 402 drive reports a fault whenever
+ its motor power is off (interlock tripped); a SAGIAN drive or pump does not."""
+ if self.is_pump:
+ return "pump"
+ return "sagian" if self.configure[0] == 0xFF else "cia402"
+
+ @property
+ def limits(self) -> AxisLimits:
+ """The limits at the head of the axis's Configure parameters."""
+ if self.is_pump:
+ values = struct.unpack_from("<8I2i", self.configure)
+ return AxisLimits(values[8], values[9], values[3], values[7], 0, values[2], values[6], 0)
+ values = struct.unpack_from("<6I2i", self.configure, 1)
+ return AxisLimits(values[6], values[7], values[1], values[3], values[5], *values[0:5:2])
+
+ @property
+ def pump_limits(self) -> PumpLimits:
+ """A syringe pump's start and cutoff velocity limits and backlash, from its Configure
+ parameters (min/max start velocity, min/max velocity, min/max cutoff velocity, min/max
+ acceleration, min/max position, backlash).
+
+ Raises:
+ ValueError: if the axis is not a pump.
+ """
+ if not self.is_pump:
+ raise ValueError(f"{self.name} is not a syringe pump")
+ values = struct.unpack_from("<8I2iH", self.configure)
+ return PumpLimits(values[0], values[1], values[4], values[5], values[10])
+
+ def check_position(self, position: int) -> None:
+ """Raise `ValueError` for a target outside the axis's position limits."""
+ limits = self.limits
+ if not limits.min_position <= position <= limits.max_position:
+ raise ValueError(
+ f"{self.name} position {position} is outside ({limits.min_position}, {limits.max_position})"
+ )
+
+
+@dataclass(frozen=True)
+class AxisMove:
+ """One axis's next move, in counts. Speeds left as None are the axis's maximum; `force` is the
+ force limit x1000 (grip and tip loading), 0 for none; `sensor` and `trigger` stop the move
+ where that sensor fires (0, 0 for none)."""
+
+ axis: str
+ position: int
+ velocity: Optional[int] = None
+ acceleration: Optional[int] = None
+ jerk: Optional[int] = None
+ force: int = 0
+ sensor: int = 0
+ trigger: int = 0
+
+
+class MotorTables:
+ """The axes of every arm type of one instrument, in the order they are configured
+ (`DeviceConfiguration.motor_tables`)."""
+
+ def __init__(self, modules: Dict[str, List[Axis]]):
+ self.modules = modules
+
+ @classmethod
+ def from_dict(cls, modules: Dict[str, Any]) -> "MotorTables":
+ """From a declared configuration's `modules` section: per arm type, its axes."""
+ return cls(
+ {
+ module: [
+ Axis(
+ a["name"],
+ a["device"],
+ a["index"],
+ bytes.fromhex(a["configure"]),
+ a.get("home_position", 0),
+ a.get("hysteresis", 0),
+ )
+ for a in axes
+ ]
+ for module, axes in modules.items()
+ }
+ )
+
+ def axes(self, module: str) -> List[Axis]:
+ """The axes of one arm type.
+
+ Raises:
+ ValueError: if the recording has no tables for that type.
+ """
+ if module not in self.modules:
+ raise ValueError(f"no motor tables recorded for a {module} arm; have {sorted(self.modules)}")
+ return self.modules[module]
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py
new file mode 100644
index 00000000000..0e33306691d
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py
@@ -0,0 +1,85 @@
+"""Motor tables: each axis's Configure parameters and the limits read from them, and the axes a pod
+gets from them. On the package's generic configuration."""
+
+import asyncio
+import unittest
+
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import (
+ generic_configuration,
+ generic_driver,
+ sealed,
+)
+
+
+class MotorTableTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.config = generic_configuration()
+ self.tables = self.config.motor_tables
+
+ def test_limits_from_configure_parameters_match_the_logged_ones(self) -> None:
+ """The limits parsed from each axis's Configure bytes are the ones the Master Controller
+ logged for it."""
+ for module, axes in self.config.modules.items():
+ for axis, logged in zip(self.tables.axes(module), axes):
+ for name, value in logged["limits"].items():
+ self.assertEqual(getattr(axis.limits, name), value, (module, axis.name, name))
+
+ def test_axes_in_configure_order(self) -> None:
+ mc = [a.name for a in self.tables.axes("multichannel")]
+ self.assertEqual(mc[:3], ["X", "Y", "Z"])
+ self.assertIn("D", mc)
+ span8 = [a.name for a in self.tables.axes("span8")]
+ for n in range(1, 9):
+ self.assertIn(f"Z{n}", span8)
+ self.assertIn(f"D{n}", span8)
+ self.assertEqual(
+ {a.drive for a in self.tables.axes("span8") if a.name.startswith("D")}, {"pump"}
+ )
+ self.assertTrue(all(a.is_pump for a in self.tables.axes("span8") if a.name.startswith("D")))
+
+ def test_position_check(self) -> None:
+ x = self.tables.axes("multichannel")[0]
+ x.check_position(350720)
+ with self.assertRaisesRegex(ValueError, "outside"):
+ x.check_position(350721)
+
+ def test_an_unknown_module_has_no_axes(self) -> None:
+ with self.assertRaisesRegex(ValueError, "no motor tables recorded for a robot arm"):
+ self.tables.axes("robot")
+
+
+class PodAxesTests(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self) -> None:
+ asyncio.get_running_loop().set_debug(False)
+
+ async def test_each_pod_gets_its_types_axes_and_declaration(self) -> None:
+ driver = generic_driver()
+ self.addAsyncCleanup(driver.stop)
+ await driver.discover()
+ left, right = driver.left_x_arm, driver.right_x_arm
+ assert left is not None and right is not None
+ self.assertEqual(
+ [a.name for a in left.axes], [a.name for a in driver.motor_tables.axes("multichannel")]
+ )
+ self.assertIs(left.declared, driver.declared.pods["left"])
+ self.assertEqual(right.axis("Z8").name, "Z8")
+ with self.assertRaisesRegex(ValueError, "has no axis 'Z8'"):
+ left.axis("Z8")
+
+ async def test_the_traverse_default_follows_biomeks_safe_height(self) -> None:
+ driver = generic_driver() # "Safe Height" unset (-100000), as on the instrument it came from
+ self.addAsyncCleanup(driver.stop)
+ await driver.discover()
+ assert driver.left_x_arm is not None
+ self.assertIsNone(driver.left_x_arm.default_minimum_traverse_height)
+ config = generic_configuration()
+ config.pods["left"].settings["GlobalMinSafeHeight"] = 30.0
+ driver = generic_driver(configuration=sealed(config))
+ self.addAsyncCleanup(driver.stop)
+ await driver.discover()
+ assert driver.left_x_arm is not None
+ self.assertEqual(driver.left_x_arm.default_minimum_traverse_height, 300.0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py
new file mode 100644
index 00000000000..444602a4932
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py
@@ -0,0 +1,279 @@
+"""A pod against itself: its gripper (and what it holds) against its pipettor, as Biomek keeps
+them apart, as pure functions.
+
+Biomek models each part of a pod as a box in 3D and refuses a pose where the gripper's boxes and
+the pipettor's overlap. Its path planner searches around that; here a move whose path would
+overlap is refused before anything is sent (`Pod.move_axes`), and the gripper's operations make
+room first (`Pod._make_room_for_gripper`).
+
+The parts, in Biomek's frame (cm; X along the rail, Y towards the front, Z up from the deck):
+
+- the gripper, about its rotation centre (`pod_geometry`: the pod's X + `GripperXOffset` −
+ `PadsCenterToRotationCenter`, its GY + `GripperYOffset` − `FingerCenterOffset`), its hand's
+ bottom at GZ + `GripperZOffset` + the fingers' height (the deepest point of the finger profile,
+ `Finger/Base`), so the fingertips are at GZ + `GripperZOffset`:
+ - the upper hand, from the lower hand's top (`Lowerhand/ZSpan`) up without end; it does not turn;
+ - the lower hand with the fingers' top part, down to the top part's depth (`TopPart/ZSpan`);
+ - the lower fingers, down to the fingertips;
+ - what it holds, from its bottom (the fingertips less the grip height) to its top;
+ the last three turned by GR; each widened by `AvoidanceMargin`;
+- a Span-8's probes: each probe a band in Y halfway to its neighbours (the end ones out to
+ `Mandrel1YOffset`), below the LLS module a box `ProbeSize` wide from the end of its tip up to
+ `MandrelExtender` above its mandrel's bottom, widened by `AvoidanceMargin` and, in Z, by
+ `AdditionalSafeHeight`; above it the probe's upper part, up without end;
+- the 96-head: its body (`HeadBodyXSpan` × `HeadBodyYSpan`, mandrel A1 at the pod's X and Y,
+ the mandrels centred), from the end of its tips up without end.
+
+A Span-8's tubing bundle (`LLSWireModel`, `span8_bundle_box`) is not one of the pipettor's parts
+here: Biomek's own prime approach sweeps the probes past the gripper parked after homing through
+that box, so what Biomek tests it against is not yet known. It is computed for drawing.
+"""
+
+import math
+from dataclasses import dataclass
+from typing import Dict, List, Optional, Sequence, Tuple
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration
+
+OPEN = 1e10 # a part with no top
+
+
+class PodCollisionError(ValueError):
+ """A move would bring a pod's gripper (or what it holds) into its own pipettor. Raised before
+ anything is sent."""
+
+
+Point = Tuple[float, float]
+
+
+@dataclass(frozen=True)
+class Part:
+ """A part of a pod at a pose: a convex outline seen from above (deck cm) and its Z range."""
+
+ name: str
+ outline: Tuple[Point, ...]
+ z_low: float
+ z_high: float
+
+
+@dataclass(frozen=True)
+class GripperState:
+ """The gripper's axes in Biomek's units (cm, degrees) and what it holds."""
+
+ gy: float
+ gz: float
+ gr: float
+ gg: float
+ held: Optional[g.HeldLabware] = None
+
+
+@dataclass(frozen=True)
+class PipettorState:
+ """The pipettor's axes in Biomek's units: a Span-8's probes' Y (`ys`), mandrel bottoms (`zs`)
+ and tip lengths below them, or the 96-head's Y and Z (one each) and its tips' length."""
+
+ ys: Tuple[float, ...]
+ zs: Tuple[float, ...]
+ tips: Tuple[float, ...]
+
+
+def _box(x0: float, x1: float, y0: float, y1: float) -> Tuple[Point, ...]:
+ return ((x0, y0), (x1, y0), (x1, y1), (x0, y1))
+
+
+def _place(outline: Sequence[Point], cx: float, cy: float, degrees: float) -> Tuple[Point, ...]:
+ c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees))
+ return tuple((cx + x * c - y * s, cy + x * s + y * c) for x, y in outline)
+
+
+def finger_depth(model: Dict) -> float:
+ """How far below the hand's bottom the fingertips are: the finger profile's deepest point."""
+ return -float(min(p["Y"] for p in model["Finger"]["Base"]))
+
+
+def gripper_parts(config: PodConfiguration, x: float, state: GripperState) -> List[Part]:
+ """The gripper's parts with the pod's X at `x`."""
+ geo, model = config.geometry, config.gripper_model
+ gm = g.GripperModel.from_bif(model)
+ margin = geo.avoidance_margin
+ cx = x + geo.gripper_x_offset - gm.pads_center_to_rotation_center
+ cy = state.gy + geo.gripper_y_offset - gm.finger_center_offset
+ depth = finger_depth(model)
+ hand = state.gz + geo.gripper_z_offset + depth # the hand's bottom
+ tips = hand - depth
+ hand_top = hand + model["Lowerhand"]["ZSpan"]
+ top_part = hand - model["Finger"]["TopPart"]["ZSpan"]
+ fixed, turning = g.gripper_boxes(gm, margin, state.gg, state.held)
+ parts = [Part("upper hand", _place(_box(*fixed[0]), cx, cy, 0.0), hand_top, OPEN)]
+ parts.append(Part("lower hand", _place(_box(*turning[0]), cx, cy, state.gr), top_part, hand_top))
+ parts.append(Part("fingers", _place(_box(*turning[1]), cx, cy, state.gr), tips, top_part))
+ if state.held is not None:
+ bottom = tips - state.held.grip_offset
+ for box in turning[2:]:
+ outline = _place(_box(*box), cx, cy, state.gr)
+ parts.append(Part("held labware", outline, bottom, bottom + state.held.height))
+ return parts
+
+
+def span8_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]:
+ """A Span-8's probes with the pod's X at `x` (probe axes at X)."""
+ geo, s = config.geometry, config.settings
+ margin, lift = geo.avoidance_margin, geo.additional_safe_height
+ half = s["ProbeSize"] / 2
+ extender = s.get("MandrelExtender", 0.0)
+ ys = state.ys
+ parts = []
+ for i, (y, z, tip) in enumerate(zip(ys, state.zs, state.tips)):
+ low = y - geo.mandrel1_y_offset if i == 0 else (ys[i - 1] + y) / 2
+ high = y + geo.mandrel1_y_offset if i == len(ys) - 1 else (y + ys[i + 1]) / 2
+ low, high = min(low, high), max(low, high)
+ lower = _box(x - half - margin, x + half + margin, low - margin, high + margin)
+ parts.append(Part(f"probe {i + 1}", lower, z - tip - lift, z + extender))
+ upper = _box(x - geo.mandrel1_x_offset - margin, x + half + margin, low - margin, high + margin)
+ parts.append(Part(f"probe {i + 1} upper part", upper, z + extender, OPEN))
+ return parts
+
+
+@dataclass(frozen=True)
+class BundleBox:
+ """The space a Span-8's tubing bundle may hang in (Biomek's frame, cm), open upward."""
+
+ x0: float
+ x1: float
+ y0: float
+ y1: float
+ z_low: float
+
+
+def span8_bundle_box(
+ config: PodConfiguration, x: float, state: PipettorState
+) -> Optional[BundleBox]:
+ """Where a Span-8's tubing bundle hangs with the probe axes at `x`, from `LLSWireModel` (None
+ without it):
+
+ - X: from the probes' axis + `WireStartXOffset` to + `AnchorXOffset`;
+ - Y: the probes' range, out to halfway towards the anchor's (`AnchorCenterY` ±
+ `AnchorHalfLength`);
+ - Z: up from the lower of where the bundle leaves the lowest probe (its mandrel's bottom +
+ `MandrelExtender` + `FixedTipZOriginToWireOffset`) and the loop's bottom, `WireBottomAtZMax`
+ less half as far as that probe is below its highest Z. The lowest probe is the one furthest
+ below its own highest Z (`Z1`..`Z8` limits).
+ No `AvoidanceMargin`: the bundle is not widened.
+ """
+ wire = config.settings.get("LLSWireModel")
+ if not wire:
+ return None
+ extender = config.settings.get("MandrelExtender", 0.0)
+ lowest = []
+ for i, z in enumerate(state.zs):
+ low, high = config.limits.get(f"Z{i + 1}", config.limits.get("Z", (z, z)))
+ z = max(low, min(high, z))
+ lowest.append((high - z, z + extender + wire["FixedTipZOriginToWireOffset"]))
+ below, leaves = max(lowest)
+ y0, y1 = min(state.ys), max(state.ys)
+ near, far = (
+ wire["AnchorCenterY"] - wire["AnchorHalfLength"],
+ wire["AnchorCenterY"] + wire["AnchorHalfLength"],
+ )
+ return BundleBox(
+ x + wire["WireStartXOffset"],
+ x + wire["AnchorXOffset"],
+ min(y0, (y0 + near) / 2),
+ max(y1, (y1 + far) / 2),
+ min(leaves, wire["WireBottomAtZMax"] - below / 2),
+ )
+
+
+def head96_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]:
+ """The 96-head with mandrel A1 at (`x`, `state.ys[0]`), its bottom at `state.zs[0]`."""
+ geo, s = config.geometry, config.settings
+ margin = geo.avoidance_margin
+ body_x, body_y = s["HeadBodyXSpan"], s["HeadBodyYSpan"]
+ grid_x = ((geo.mandrels_x or 1) - 1) * geo.mandrel_x_spacing
+ grid_y = ((geo.mandrels_y or 1) - 1) * geo.mandrel_y_spacing
+ left = x - (body_x - grid_x) / 2
+ back = state.ys[0] - (body_y - grid_y) / 2 # A1 is the back row; Y runs to the front
+ outline = _box(left - margin, left + body_x + margin, back - margin, back + body_y + margin)
+ return [Part("96-head", outline, state.zs[0] - state.tips[0], OPEN)]
+
+
+def pipettor_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]:
+ if config.module_type == "span8":
+ return span8_parts(config, x, state)
+ return head96_parts(config, x, state)
+
+
+def _axes(outline: Sequence[Point]) -> List[Point]:
+ n = len(outline)
+ return [
+ (outline[i][1] - outline[(i + 1) % n][1], outline[(i + 1) % n][0] - outline[i][0])
+ for i in range(n)
+ ]
+
+
+def overlap(a: Part, b: Part) -> bool:
+ """Whether two parts share any volume (touching is clear): Z ranges, then separating axes."""
+ if a.z_high <= b.z_low or b.z_high <= a.z_low:
+ return False
+ for ax, ay in _axes(a.outline) + _axes(b.outline):
+ pa = [px * ax + py * ay for px, py in a.outline]
+ pb = [px * ax + py * ay for px, py in b.outline]
+ if max(pa) <= min(pb) or max(pb) <= min(pa):
+ return False
+ return True
+
+
+def collisions(
+ config: PodConfiguration, x: float, gripper: GripperState, pipettor: PipettorState
+) -> List[Tuple[str, str]]:
+ """The (gripper part, pipettor part) pairs that overlap at this pose."""
+ gp, pp = gripper_parts(config, x, gripper), pipettor_parts(config, x, pipettor)
+ return [(a.name, b.name) for a in gp for b in pp if overlap(a, b)]
+
+
+# cm: the most any point moves between two checked poses. Every part is widened by
+# `AvoidanceMargin` (0.2164 cm), so a contact cannot pass between two steps unseen.
+SWEEP_STEP = 0.1
+
+
+def swept_collisions(
+ config: PodConfiguration,
+ x: Tuple[float, float],
+ gripper: Tuple[GripperState, GripperState],
+ pipettor: Tuple[PipettorState, PipettorState],
+) -> List[Tuple[str, str]]:
+ """The overlaps anywhere along a coordinated move (every axis on the same profile, scaled to its
+ distance), checked at steps no point covers more than `SWEEP_STEP` in. The parts are widened by
+ `AvoidanceMargin`, more than a step."""
+ (g0, g1), (p0, p1) = gripper, pipettor
+ # X carries every part alike, so only the other axes change what overlaps.
+ reach = config.gripper_model["Finger"]["PadsCenterToRotationCenter"] + 15.0
+ travel = max(
+ [abs(g1.gy - g0.gy), abs(g1.gz - g0.gz), abs(g1.gg - g0.gg)]
+ + [reach * math.radians(abs(g1.gr - g0.gr))]
+ + [abs(b - a) for a, b in zip(p0.ys, p1.ys)]
+ + [abs(b - a) for a, b in zip(p0.zs, p1.zs)]
+ )
+ steps = max(1, math.ceil(travel / SWEEP_STEP))
+ found: List[Tuple[str, str]] = []
+ for i in range(steps + 1):
+ t = i / steps
+
+ def lerp(a: float, b: float) -> float:
+ return float(a + t * (b - a))
+
+ gs = GripperState(
+ lerp(g0.gy, g1.gy), lerp(g0.gz, g1.gz), lerp(g0.gr, g1.gr), lerp(g0.gg, g1.gg), g0.held
+ )
+ ps = PipettorState(
+ tuple(lerp(a, b) for a, b in zip(p0.ys, p1.ys)),
+ tuple(lerp(a, b) for a, b in zip(p0.zs, p1.zs)),
+ p0.tips,
+ )
+ for pair in collisions(config, lerp(*x), gs, ps):
+ if pair not in found:
+ found.append(pair)
+ if found:
+ return found
+ return found
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py
new file mode 100644
index 00000000000..cecd76051de
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py
@@ -0,0 +1,104 @@
+"""The pod's own collision check: the gripper against the pipettor."""
+
+import dataclasses
+import unittest
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc
+from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration
+
+
+class PodCollisionTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.right = generic_configuration().pod("right")
+
+ def probes(self, y: float, z: float, span: float = 6.3, tip: float = 0.0) -> pc.PipettorState:
+ return pc.PipettorState(tuple(y + i * span / 7 for i in range(8)), (z,) * 8, (tip,) * 8)
+
+ def test_the_parked_gripper_is_clear_of_the_probes(self) -> None:
+ # The park: GR 90, GY 48, GZ at its top, GG 7.889; the probes over the wash station.
+ gripper = pc.GripperState(48.0, 37.8, 90.0, 7.889)
+ self.assertEqual(pc.collisions(self.right, 120.0, gripper, self.probes(58.275, 39.1)), [])
+
+ def test_fingers_turned_under_the_probes_collide(self) -> None:
+ # GR 0 points the fingers along +X, under the probe axes; with the probes over them in Y
+ # and the fingers' top above the probes' tips, they meet.
+ gripper = pc.GripperState(30.0, 30.0, 0.0, 9.0)
+ found = pc.collisions(self.right, 120.0, gripper, self.probes(28.0, 20.0))
+ self.assertIn(("fingers", "probe 1"), found)
+
+ def test_probes_at_the_far_end_of_y_clear_the_turned_fingers(self) -> None:
+ # Logged before a turn to 0 degrees with GY 61.26: the probes sent to Y 15.274, span 6.3.
+ gripper = pc.GripperState(61.263, 30.0, 0.0, 9.706)
+ self.assertEqual(pc.collisions(self.right, 120.0, gripper, self.probes(15.274, 20.0)), [])
+
+ def test_held_labware_counts(self) -> None:
+ held = g.HeldLabware(12.78, 8.56, height=1.41, grip_offset=-0.23)
+ gripper = pc.GripperState(30.0, 30.0, 0.0, 8.5, held)
+ self.assertIn("held labware", [p.name for p in pc.gripper_parts(self.right, 120.0, gripper)])
+
+ def test_a_turn_through_the_probes_is_caught_on_its_way(self) -> None:
+ # From 180 degrees (fingers away from the probes) to 90: never under the probes. To 0 and
+ # back is caught at 0, the end; a sweep from 180 to -90 passes 0 only between its ends.
+ a = pc.GripperState(30.0, 30.0, 180.0, 9.0)
+ b = pc.GripperState(30.0, 30.0, -180.0, 9.0)
+ probes = self.probes(28.0, 20.0)
+ self.assertEqual(pc.collisions(self.right, 120.0, a, probes), [])
+ self.assertEqual(pc.collisions(self.right, 120.0, b, probes), [])
+ found = pc.swept_collisions(self.right, (120.0, 120.0), (a, b), (probes, probes))
+ self.assertTrue(found)
+
+ def bundle(self, z: float = 30.0) -> pc.BundleBox:
+ box = pc.span8_bundle_box(self.right, 120.0, self.probes(28.0, z))
+ assert box is not None
+ return box
+
+ def test_the_tubing_bundle_hangs_beside_the_probes_towards_its_anchor(self) -> None:
+ wire = self.right.settings["LLSWireModel"]
+ box = self.bundle()
+ self.assertAlmostEqual(box.x0, 120.0 + wire["WireStartXOffset"])
+ self.assertAlmostEqual(box.x1, 120.0 + wire["AnchorXOffset"])
+ # The anchor is in front of these probes: the box reaches halfway to its far end.
+ self.assertAlmostEqual(box.y0, 28.0)
+ far = wire["AnchorCenterY"] + wire["AnchorHalfLength"]
+ self.assertAlmostEqual(box.y1, (34.3 + far) / 2)
+
+ def test_the_bundle_loop_drops_half_as_far_as_the_lowest_probe(self) -> None:
+ # Low enough that the loop's bottom, not where the bundle leaves the probes, is lowest.
+ self.assertAlmostEqual(self.bundle(26.0).z_low - self.bundle(30.0).z_low, -2.0)
+ # At the top the bundle leaves the probes below the loop's bottom.
+ wire, s = self.right.settings["LLSWireModel"], self.right.settings
+ top = self.right.limits["Z1"][1]
+ top_box = pc.span8_bundle_box(
+ self.right, 120.0, pc.PipettorState((28.0,) * 8, (top,) * 8, (0.0,) * 8)
+ )
+ assert top_box is not None
+ self.assertLessEqual(
+ top_box.z_low, top + s["MandrelExtender"] + wire["FixedTipZOriginToWireOffset"]
+ )
+
+ def test_the_bundle_does_not_guard_the_gripper(self) -> None:
+ # Biomek's prime approach sweeps the probes from Y 15.1 to 58.3 with the gripper as homing
+ # left it (GR -2.2 degrees, GY 39.9, at its top); around Y 47 the bundle's box covers the
+ # fingers, and Biomek sends the move all the same.
+ gripper = pc.GripperState(39.9, 37.931, -2.18, 7.937)
+ probes = self.probes(47.86, 39.2)
+ box = pc.span8_bundle_box(self.right, 145.4, probes)
+ assert box is not None
+ fingers = next(p for p in pc.gripper_parts(self.right, 145.4, gripper) if p.name == "fingers")
+ self.assertTrue(
+ pc.overlap(
+ fingers, pc.Part("bundle", pc._box(box.x0, box.x1, box.y0, box.y1), box.z_low, pc.OPEN)
+ )
+ )
+ self.assertEqual(pc.collisions(self.right, 145.4, gripper, probes), [])
+
+ def test_a_span8_without_a_bundle_model_has_no_bundle(self) -> None:
+ config = dataclasses.replace(
+ self.right, settings={k: v for k, v in self.right.settings.items() if k != "LLSWireModel"}
+ )
+ self.assertIsNone(pc.span8_bundle_box(config, 120.0, self.probes(28.0, 30.0)))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py
new file mode 100644
index 00000000000..56a0ee26540
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py
@@ -0,0 +1,371 @@
+"""Where a pod is along the shared X rail: Biomek's collision model, as pure functions.
+
+Biomek's rule:
+
+- A pod's X range at a pose is the union of its bridge, its pipettor (widened by the avoidance
+ margin) and its gripper.
+- The gripper is boxes, each widened by the avoidance margin, in the gripper's own frame:
+ - the upper hand, which does not turn;
+ - the lower hand with the top of the fingers;
+ - the lower fingers;
+ - the held labware, if any.
+
+ The fingers open to the grip width, or wider to clear the labware. Every box but the upper
+ hand turns by GR about the rotation centre, then all move with the gripper. The rotation
+ centre's deck X is the pod's X + `GripperXOffset` - `PadsCenterToRotationCenter`. GR = 0 points
+ the fingers to +X (GR ~90 to the front, ~189 at its maximum).
+- A move's swept range comes from its start and end poses.
+- Two ranges collide when their edges, floored to 1/16 cm cells, overlap or share a cell
+ (`grid_overlap`).
+
+Everything is in Biomek's units: deck X in cm, GR in degrees, the grip width GG in cm. A pod's X
+is `PodConfiguration.to_value("X", counts)`, and its GR and GG likewise.
+
+Where this differs from Biomek, it says so:
+- **Sweeps.** Biomek's swept range is the union of the start and end poses. Here a move's sweep
+ follows its coordinated path (`swept_x_range`), so a gripper turning through the other pod's
+ side between those poses is caught. This is never looser.
+- **Held labware.** Biomek reads its size, and the stack on it, from its labware library. Here the
+ caller gives it, from the resource the gripper holds (`HeldLabware`).
+"""
+
+import math
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Sequence, Tuple
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import Obstacle, PodGeometry
+
+Range = Tuple[float, float]
+"""An X interval in deck cm, `(lowest, highest)`."""
+
+Box = Tuple[float, float, float, float]
+"""A box in the gripper's frame, seen from above: `(x_low, x_high, y_low, y_high)`, cm. x runs
+along the fingers, y across them, from the rotation centre."""
+
+
+@dataclass(frozen=True)
+class GripperModel:
+ """The gripper's dimensions, in cm, from the instrument file's `GripperModel`, named after its
+ keys."""
+
+ upperhand_x_span: float
+ upperhand_y_span: float
+ upperhand_center_x: float
+ upperhand_center_y: float
+ lowerhand_fingerwise_span: float
+ lowerhand_default_span: float
+ finger_fingerwise_offset: float
+ finger_extension_span: float
+ top_part_fingerwise_span: float
+ bottom_part_fingerwise_span: float
+ finger_thickness: float
+ clipper_thickness: float
+ lw_finger_spacing: float
+ finger_center_offset: float
+ overall_angled_thickness: float
+ pads_center_to_rotation_center: float
+
+ @classmethod
+ def from_bif(cls, model: Dict[str, Any]) -> "GripperModel":
+ """From the declared configuration's `gripper_model` (the `.bif` `GripperModel` dict)."""
+ up, low, finger = model["Upperhand"], model["Lowerhand"], model["Finger"]
+ return cls(
+ upperhand_x_span=up["XSpan"],
+ upperhand_y_span=up["YSpan"],
+ upperhand_center_x=up["CenterXOffset"],
+ upperhand_center_y=up["CenterYOffset"],
+ lowerhand_fingerwise_span=low["FingerwiseSpan"],
+ lowerhand_default_span=low["YSpanNoFingerMountExtension"],
+ finger_fingerwise_offset=finger["FingerwiseOffset"],
+ finger_extension_span=finger["ExtensionSpan"],
+ top_part_fingerwise_span=finger["TopPart"]["FingerwiseSpan"],
+ bottom_part_fingerwise_span=finger["BottomPart"]["FingerwiseSpan"],
+ finger_thickness=finger["Thickness"],
+ clipper_thickness=finger["ClipperThickness"],
+ lw_finger_spacing=finger["LWFingerSpacing"],
+ finger_center_offset=finger["FingerCenterOffset"],
+ overall_angled_thickness=finger["OverallAngledThickness"],
+ pads_center_to_rotation_center=finger["PadsCenterToRotationCenter"],
+ )
+
+
+@dataclass(frozen=True)
+class StackedLayer:
+ """A layer stacked on what the gripper holds (a lid on a plate), in the gripper's frame, cm: its
+ footprint's `length` along the fingers and `width` across them, and where its corner is from
+ the corner of the layer below (`dx`, `dy`)."""
+
+ dx: float
+ dy: float
+ length: float
+ width: float
+
+
+@dataclass(frozen=True)
+class HeldLabware:
+ """What the gripper holds, in its own frame, cm: `length` along the fingers, `width` between
+ them; offsets move it from the centre of the pads. `layers` are what is stacked on it, bottom
+ up (as Biomek counts it: the gripped labware is a stack; the bottom layer is centred on the
+ pads less `GrippedLabwareOffsets`, each layer above sits at its offset from the corner of the
+ one below, and the footprint is every layer's box). The grip width is the bottom layer's.
+ `height` is the stack's, from its bottom to its top; `grip_offset` how far above its bottom the
+ fingertips are (negative below it)."""
+
+ length: float
+ width: float
+ offset_x: float = 0.0
+ offset_y: float = 0.0
+ layers: Tuple[StackedLayer, ...] = ()
+ height: float = 0.0
+ grip_offset: float = 0.0
+
+
+@dataclass(frozen=True)
+class GripperPose:
+ """The gripper's rotation `gr` (degrees) and grip width `gg` (cm), and what it holds."""
+
+ gr: float
+ gg: float
+ held: Optional[HeldLabware] = None
+
+
+def bridge_x_range(geometry: PodGeometry, x: float) -> Range:
+ low = x - geometry.bridge_to_head_x_offset - geometry.mandrel1_x_offset
+ return low, low + geometry.bridge_x_span
+
+
+def pipettor_x_span(geometry: PodGeometry) -> float:
+ """The pipettor's X extent: the pod's `PodXSpan` in the instrument file, 18.606 cm on the
+ Multichannel, 4.0 on the Span-8."""
+ return geometry.pod_x_span
+
+
+def pipettor_x_range(geometry: PodGeometry, x: float) -> Range:
+ low = x - geometry.mandrel1_x_offset
+ margin = geometry.avoidance_margin
+ return low - margin, low + pipettor_x_span(geometry) + margin
+
+
+def union(a: Range, b: Range) -> Range:
+ return min(a[0], b[0]), max(a[1], b[1])
+
+
+def gripper_boxes(
+ model: GripperModel, margin: float, gg: float, held: Optional[HeldLabware]
+) -> Tuple[List[Box], List[Box]]:
+ """The gripper's boxes in its frame, each widened by `margin`. Returns the boxes
+ that stay put (the upper hand) and those that turn with GR."""
+ m = model
+ opening = (m.lw_finger_spacing + m.finger_thickness) * 2 + max(gg, 0.0)
+ if held is not None:
+ finger = m.lw_finger_spacing + m.clipper_thickness + m.finger_thickness
+ opening = max(opening, 2 * finger + held.width)
+ finger_y_high = opening / 2 + m.finger_center_offset
+ finger_y_low = m.finger_center_offset - opening / 2
+ hand_span = max((m.finger_extension_span + m.finger_thickness) * 2 - opening, opening)
+ hand_y_low = min(-m.lowerhand_default_span / 2, m.finger_center_offset - hand_span / 2)
+ hand_y_high = max(m.lowerhand_default_span / 2, hand_span / 2 + m.finger_center_offset)
+ top_end = m.top_part_fingerwise_span - m.lowerhand_fingerwise_span / 2
+ top_end += m.finger_fingerwise_offset
+
+ def box(x0: float, x1: float, y0: float, y1: float) -> Box:
+ return x0 - margin, x1 + margin, y0 - margin, y1 + margin
+
+ upperhand = box(
+ m.upperhand_center_x - m.upperhand_x_span / 2,
+ m.upperhand_center_x + m.upperhand_x_span / 2,
+ m.upperhand_center_y - m.upperhand_y_span / 2,
+ m.upperhand_center_y + m.upperhand_y_span / 2,
+ )
+ turning = [
+ # the lower hand with the top portion of the fingers
+ box(
+ -m.lowerhand_fingerwise_span / 2,
+ top_end,
+ min(finger_y_low, hand_y_low),
+ max(finger_y_high, hand_y_high),
+ ),
+ # the lower portion of the fingers
+ box(top_end, top_end + m.bottom_part_fingerwise_span, finger_y_low, finger_y_high),
+ ]
+ if held is not None:
+ x0 = m.pads_center_to_rotation_center - held.offset_x - held.length / 2
+ y0 = m.finger_center_offset - held.offset_y - held.width / 2
+ turning.append(box(x0, x0 + held.length, y0, y0 + held.width))
+ for layer in held.layers:
+ x0, y0 = x0 + layer.dx, y0 + layer.dy
+ turning.append(box(x0, x0 + layer.length, y0, y0 + layer.width))
+ return [upperhand], turning
+
+
+def turned_x_extent(box: Box, start: float, end: float) -> Range:
+ """The X a box covers while turning about the origin from `start` to `end` degrees
+ (counterclockwise from +X). Each corner's X is r cos(angle + phase); between the ends it peaks
+ where that angle crosses a multiple of 180 degrees."""
+ low_angle, high_angle = min(start, end), max(start, end)
+ xs: List[float] = []
+ for x in (box[0], box[1]):
+ for y in (box[2], box[3]):
+ r, phase = math.hypot(x, y), math.degrees(math.atan2(y, x))
+ angles = [low_angle, high_angle]
+ k = math.ceil((low_angle + phase) / 180.0)
+ while k * 180.0 - phase <= high_angle:
+ angles.append(k * 180.0 - phase)
+ k += 1
+ xs.extend(r * math.cos(math.radians(a + phase)) for a in angles)
+ return min(xs), max(xs)
+
+
+def gripper_x_range(
+ geometry: PodGeometry,
+ model: GripperModel,
+ x: float,
+ start: GripperPose,
+ end: Optional[GripperPose] = None,
+) -> Range:
+ """The X the gripper covers with the pod at `x`, at `start`, or turning and opening from
+ `start` to `end`."""
+ end = end or start
+ centre = x + geometry.gripper_x_offset - model.pads_center_to_rotation_center
+ margin = geometry.avoidance_margin
+ gg = max(start.gg, end.gg)
+ low, high = math.inf, -math.inf
+ for held in {start.held, end.held}:
+ fixed, turning = gripper_boxes(model, margin, gg, held)
+ for b in fixed:
+ low, high = min(low, centre + b[0]), max(high, centre + b[1])
+ for b in turning:
+ lo, hi = turned_x_extent(b, start.gr, end.gr)
+ low, high = min(low, centre + lo), max(high, centre + hi)
+ return low, high
+
+
+@dataclass(frozen=True)
+class Gripper:
+ """A gripper on a pod, at a pose: what the X range needs to count it."""
+
+ model: GripperModel
+ pose: GripperPose
+
+
+def pod_x_range(geometry: PodGeometry, x: float, gripper: Optional[Gripper] = None) -> Range:
+ """The X a pod takes up with its X at `x` and its gripper at its pose. Without
+ a gripper, its bridge and pipettor only."""
+ base = union(bridge_x_range(geometry, x), pipettor_x_range(geometry, x))
+ if gripper is None:
+ return base
+ return union(base, gripper_x_range(geometry, gripper.model, x, gripper.pose))
+
+
+SWEEP_TOLERANCE = 0.02
+"""How far, in cm, any point may move between two of the poses a sweep checks; the result is
+widened by it, so it is never looser than the continuous move."""
+
+
+def swept_x_range(
+ geometry: PodGeometry,
+ start: float,
+ end: float,
+ gripper_start: Optional[Gripper] = None,
+ gripper_end: Optional[Gripper] = None,
+) -> Range:
+ """The X a pod takes up while moving its X from `start` to `end`, and its
+ gripper from one pose to the other.
+
+ A coordinated move (`motion.py`, the Master Controller's `AM`) takes every axis along the same
+ profile, scaled to its distance, so the pod passes through X(s) and GR(s), GG(s) together for
+ s from 0 to 1. The sweep follows that path, at steps no point can cover more than
+ `SWEEP_TOLERANCE` in, widened by it. Biomek checks the start and end poses only; a gripper
+ turning through the other pod's side between them is caught here."""
+ if gripper_start is None:
+ return union(pod_x_range(geometry, start), pod_x_range(geometry, end))
+ model = gripper_start.model
+ a, b = gripper_start.pose, (gripper_end or gripper_start).pose
+ swept = union(
+ pod_x_range(geometry, start, gripper_start), pod_x_range(geometry, end, Gripper(model, b))
+ )
+ if (a.gr, a.gg, a.held) == (b.gr, b.gg, b.held):
+ return swept # the footprint only translates with X: its two ends bound it exactly
+ reach = max(
+ math.hypot(max(abs(box[0]), abs(box[1])), max(abs(box[2]), abs(box[3])))
+ for held in {a.held, b.held}
+ for boxes in gripper_boxes(model, geometry.avoidance_margin, max(a.gg, b.gg), held)
+ for box in boxes
+ )
+ # Between two steps the footprint translates (bounded by the steps themselves) and turns and
+ # opens, by at most this far:
+ travel = reach * math.radians(abs(b.gr - a.gr)) + abs(b.gg - a.gg)
+ steps = max(1, math.ceil(travel / SWEEP_TOLERANCE))
+ low, high = swept
+ for i in range(steps + 1):
+ s = i / steps
+ pose = GripperPose(a.gr + s * (b.gr - a.gr), a.gg + s * (b.gg - a.gg), a.held)
+ x = start + s * (end - start)
+ for held in {a.held, b.held}:
+ lo, hi = gripper_x_range(geometry, model, x, GripperPose(pose.gr, pose.gg, held))
+ low, high = min(low, lo), max(high, hi)
+ return low - SWEEP_TOLERANCE, high + SWEEP_TOLERANCE
+
+
+def overlap(a: Range, b: Range) -> bool:
+ """Whether two ranges share any X. Touching is not overlapping."""
+ return a[0] < b[1] and b[0] < a[1]
+
+
+# Biomek compares range edges as whole sixteenths of a cm, rounded down (`floor(x * 16)`).
+GRID_PER_CM = 16
+
+
+def grid_cell(x: float) -> int:
+ return math.floor(x * GRID_PER_CM)
+
+
+def grid_overlap(a: Range, b: Range) -> bool:
+ """Biomek's collision test: each edge floored to its 1/16 cm cell; the ranges
+ collide unless one's high cell is below the other's low cell. Edges in the same cell collide."""
+ return not (grid_cell(a[1]) < grid_cell(b[0]) or grid_cell(b[1]) < grid_cell(a[0]))
+
+
+def pod_xy_box(geometry: PodGeometry, x: float, y: float) -> Tuple[Range, Range]:
+ """The pod's body seen from above at X `x`, Y `y` (mandrel A1 / probe 1), cm: its corner is
+ `Mandrel1XOffset` / `Mandrel1YOffset` back from that."""
+ x0, y0 = x - geometry.mandrel1_x_offset, y - geometry.mandrel1_y_offset
+ return (x0, x0 + geometry.pod_x_span), (y0, y0 + geometry.pod_y_span)
+
+
+def _open_overlap(low: Optional[float], high: Optional[float], span: Range, buffer: float) -> bool:
+ lo = -math.inf if low is None else low - buffer
+ hi = math.inf if high is None else high + buffer
+ return lo < span[1] and span[0] < hi
+
+
+@dataclass(frozen=True)
+class Clearance:
+ """What a pod's travel over an X/Y area must clear: the lowest height (cm) its channels may
+ travel at, and the obstacles in the way that no height clears (walls)."""
+
+ height: float
+ walls: Tuple[str, ...]
+
+
+def obstacle_clearance(obstacles: Sequence[Obstacle], x: Range, y: Range) -> Clearance:
+ """Over the area `x` by `y` (cm): the top (plus buffer) of every obstacle there with a top and
+ no floor (the pump bank), and every obstacle there with no top (a wall, or a ceiling).
+
+ Ceilings (a bottom and no top: the I-beam from Z 37.069 behind Y 11.092, the cameras from Z 32.078
+ at the front corners) count as walls. Biomek makes every obstacle a box (an open top at 1e10,
+ each face widened by its buffer) and checks the pod's whole part model against
+ them, the carriage above the channels included, so a ceiling bounds the pod's body, not its
+ channels' bottom; with the channels at a traverse height the body is above every ceiling. None of
+ the 12,321 X/Y moves Biomek logged put a pod's body under one (the furthest back was Y 14.27 cm),
+ so blocking them refuses nothing Biomek did."""
+ height = -math.inf
+ walls = []
+ for o in obstacles:
+ if not (_open_overlap(o.x1, o.x2, x, o.buffer) and _open_overlap(o.y1, o.y2, y, o.buffer)):
+ continue
+ if o.z2 is None:
+ walls.append(o.name)
+ elif o.z2 is not None and (o.z1 is None or o.z1 < 0):
+ height = max(height, o.z2 + o.buffer)
+ return Clearance(height, tuple(walls))
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_move_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_move_tests.py
new file mode 100644
index 00000000000..99d777b879f
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_move_tests.py
@@ -0,0 +1,180 @@
+"""A pod's coordinated move (`Pod.move_axes`), against a simulated instrument: what each board is
+sent, and the position record kept as the Master Controller keeps it."""
+
+import struct
+from typing import List, Tuple
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import motion
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import NotHomedError
+from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod
+from pylabrobot.beckman_coulter.biomek_i7.driver.homing_tests import SimulatedRunTest
+from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import (
+ generic_configuration,
+ sealed,
+)
+
+SPAN8_MOTORS = 21 # X, Y1-Y8, Z1-Z8, GY, GG, GZ, GR: every Span-8 axis but the pumps
+
+
+class PodMoveTest(SimulatedRunTest):
+ """Helpers for tests on homed simulated pods."""
+
+ async def homed(self, homed=True, configuration=None) -> BiomekI7Driver:
+ driver = await self.start(homed, configuration=configuration)
+ await driver.home()
+ self.mark(driver)
+ return driver
+
+ def sent(self, driver: BiomekI7Driver, module: str) -> List[Tuple[str, bytes]]:
+ """(command name, parameters) of each request a board was sent since the mark."""
+ requests = self.usb(driver, module).requests[self.marks[module] :]
+ return [(p.COMMANDS[(m[0], m[4])], m[5:]) for m in requests]
+
+ def pod(self, driver: BiomekI7Driver, side: str) -> Pod:
+ pod = driver.left_x_arm if side == "left" else driver.right_x_arm
+ assert pod is not None
+ return pod
+
+
+class PodMoveTests(PodMoveTest):
+ async def test_first_move_reads_positions_then_moves_together(self) -> None:
+ driver = await self.homed()
+ pod = self.pod(driver, "left")
+ usb = self.usb(driver, "multichannel")
+ before = {a.name: (usb.axis_model(a.name).position,) * 2 for a in pod.axes}
+ expected = motion.plan_move(pod.axes, before, {"X": 100000, "Y": 50000})
+ unknown = sum(1 for c in pod.cpositions.values() if c[0] is None) # every axis homed
+ self.assertGreaterEqual(unknown, 7)
+ result = await pod.move_axes({"X": 100000, "Y": 50000})
+ motions = result.motions
+ self.assertEqual(motions, expected[0])
+ self.assertEqual(result.completions, {})
+ names = [n for n, _ in self.sent(driver, "multichannel")]
+ # enable-all: the positions are unknown after homing.
+ n = 1 + 2 * unknown
+ self.assertEqual(names[0], "Stop Motion Service")
+ self.assertEqual(names[1 : 1 + unknown], ["Set State"] * unknown)
+ self.assertEqual(names[1 + unknown : n], ["Get Current Position"] * unknown)
+ self.assertEqual(names[n:], ["Set Move Parameters"] * 2 + ["Move All"])
+ sent = self.sent(driver, "multichannel")
+ for m, (_, params) in zip(motion.spawn_order(motions), sent[n : n + 2]):
+ self.assertEqual(
+ struct.unpack(" None:
+ driver = await self.homed()
+ pod = self.pod(driver, "left")
+ await pod.move_axes({"X": 100000})
+ self.mark(driver)
+ (x,) = (await pod.move_axes({"X": 50000, "Y": 0})).motions # Y is already at 0
+ self.assertEqual(
+ [n for n, _ in self.sent(driver, "multichannel")], ["Set Move Parameters", "Move All"]
+ )
+ self.assertEqual((x.axis, x.velocity), ("X", pod.axis("X").limits.max_velocity))
+
+ async def test_nothing_is_sent_when_every_axis_is_there(self) -> None:
+ driver = await self.homed()
+ pod = self.pod(driver, "left")
+ await pod.move_axes({"X": 100000})
+ self.mark(driver)
+ self.assertEqual((await pod.move_axes({"X": 100000})).motions, [])
+ self.assertEqual(self.sent(driver, "multichannel"), [])
+
+ async def test_bad_requests_send_nothing(self) -> None:
+ driver = await self.homed()
+ pod = self.pod(driver, "right")
+ for targets, speed, forces in (
+ ({"X": 10**7}, 1000, {}),
+ ({"X": -100}, 0, {}),
+ ({"Q": 1}, 1000, {}),
+ ({"Z1": -1000}, 1000, {"Z2": 1.0}), # a force on an axis without a target
+ ({"Z1": -1000}, 1000, {"Z1": -1.0}),
+ ):
+ with self.subTest(targets=targets, speed=speed), self.assertRaises(ValueError):
+ await pod.move_axes(targets, speed, forces=forces)
+ with self.assertRaises(RuntimeError): # its valve has not been set
+ await pod.move_axes({"D1": 100})
+ self.assertEqual(self.sent(driver, "span8"), [])
+
+ async def test_span8_z_moves_down_by_its_hysteresis_more(self) -> None:
+ # Hysteresis is measured per instrument; the generic configuration has none, so this test
+ # gives two channels some.
+ config = generic_configuration()
+ for axis in config.modules["span8"]:
+ if axis["name"] in ("Z1", "Z2"):
+ axis["hysteresis"] = -57
+ driver = await self.homed(configuration=sealed(config))
+ pod = self.pod(driver, "right")
+ await pod.move_axes({"Z1": -20000, "Z2": -20000})
+ names = [n for n, _ in self.sent(driver, "span8")]
+ self.assertEqual(names[1 : 1 + 2 * SPAN8_MOTORS].count("Get Current Position"), SPAN8_MOTORS)
+ usb = self.usb(driver, "span8")
+ for name in ("Z1", "Z2"):
+ h = pod.axis(name).hysteresis
+ self.assertLess(h, 0)
+ self.assertEqual(usb.axis_model(name).position, -20000 + h)
+ self.assertEqual(pod.cpositions[name], (-20000 + h, -20000))
+ # Back up: the move takes up the hysteresis, and the channel ends at its target.
+ await pod.move_axes({"Z1": -10000})
+ self.assertEqual(usb.axis_model("Z1").position, -10000)
+ self.assertEqual(pod.cpositions["Z1"], (-10000, -10000))
+
+ async def test_not_homed_axis_drops_the_move_and_forgets_positions(self) -> None:
+ driver = await self.homed()
+ pod = self.pod(driver, "left")
+ self.usb(driver, "multichannel").axis_model("Y").homed = False # as after a power cycle
+ with self.assertRaises(NotHomedError):
+ await pod.move_axes({"X": 1000, "Y": 1000})
+ self.assertEqual(self.sent(driver, "multichannel")[-1][0], "Stop Motion Service")
+ self.assertTrue(all(c[0] is None for c in pod.cpositions.values()))
+
+ async def test_homing_forgets_positions(self) -> None:
+ driver = await self.homed()
+ pod = self.pod(driver, "left")
+ await pod.move_axes({"X": 100000})
+ await pod.home()
+ self.assertEqual(pod.cpositions["X"], (None, pod.axis("X").home_position))
+
+ async def test_sensor_stop_is_reported_with_its_position(self) -> None:
+ driver = await self.homed()
+ pod = self.pod(driver, "right")
+ z1 = self.usb(driver, "span8").axis_model("Z1")
+ await pod.move_axes({"Z1": -10000})
+ z1.sensed_at = -150000
+ result = await pod.move_axes({"Z1": -200000, "Z2": -200000}, sensors={"Z1": (1, 1)})
+ self.assertEqual(result.completions["Z1"].outcome, "liquid-sensed")
+ self.assertEqual(result.stopped_at("Z1"), -150000)
+ self.assertIsNone(result.stopped_at("Z2"))
+ # The reported position is taken as Z1's, as the Master Controller takes it, with its hysteresis as for any move.
+ self.assertEqual(pod.cpositions["Z1"][0], -150000)
+ self.assertIsNotNone(pod.cpositions["Z2"][0])
+
+ async def test_both_pods_move_together(self) -> None:
+ driver = await self.homed()
+ results = await driver.move_axes({"left": {"Y": 20000}, "right": {"Z1": -10000}})
+ self.assertEqual(sorted(results), ["left", "right"])
+ self.assertEqual([m.axis for m in results["left"].motions], ["Y"])
+ self.assertEqual(self.pod(driver, "right").cpositions["Z1"][1], -10000)
+ with self.assertRaises(ValueError):
+ await driver.move_axes({"middle": {"X": 0}})
+
+ async def test_span8_takes_y_and_span_as_biomek_sends_them(self) -> None:
+ driver = await self.homed()
+ pod = self.pod(driver, "right")
+ # As logged: `AM 7 1000 0 -230264 154304 0` puts every channel at Y 154304 (S 6.3 cm, 0 counts).
+ await pod.move_axes({"Y": 154304, "S": 0})
+ self.assertEqual({pod.cpositions[f"Y{i}"][1] for i in range(1, 9)}, {154304})
+ await pod.move_axes({"S": 7000}) # Y kept: channel i 1000 counts further each
+ self.assertEqual(
+ [pod.cpositions[f"Y{i}"][1] for i in range(1, 9)], [154304 + 1000 * i for i in range(8)]
+ )
+ with self.assertRaises(ValueError):
+ await pod.move_axes({"Y": 0, "Y3": 0})
+ with self.assertRaises(ValueError):
+ await pod.move_axes({"S": -1})
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_tests.py
new file mode 100644
index 00000000000..67df383c38a
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_tests.py
@@ -0,0 +1,141 @@
+"""A pod's drive commands, checked on the wire against a fake board.
+
+Where a command has a counterpart in the Master Controller's log, the expected bytes are that
+logged message (sequence number aside).
+"""
+
+import asyncio
+import unittest
+from typing import List
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard
+from pylabrobot.beckman_coulter.biomek_i7.driver.board_tests import (
+ FakeAceUSB,
+ accepted,
+ done,
+ recorder,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import InterlockTrippedError
+from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod
+from pylabrobot.beckman_coulter.biomek_i7.driver.framing import split
+from pylabrobot.beckman_coulter.biomek_i7.driver.motors import AxisMove
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration
+
+TABLES = generic_configuration().motor_tables
+
+
+def without_sequence(message: bytes) -> bytes:
+ return message[:3] + b"\x00" + message[4:]
+
+
+def logged(hex_message: str) -> bytes:
+ return without_sequence(bytes.fromhex(hex_message))
+
+
+def answer_like_a_board(message: bytes) -> List[bytes]:
+ if message[4] in (0x50, 0x51):
+ return [accepted(message), done(message)]
+ return [done(message)]
+
+
+class PodDriveCommandTests(unittest.IsolatedAsyncioTestCase):
+ async def make_pod(self, module: str, side: str) -> Pod:
+ self.usb = FakeAceUSB(answer_like_a_board)
+ board = AceBoard(io=self.usb, default_timeout=1)
+ await board.setup()
+ self.addAsyncCleanup(board.stop)
+ return Pod(board, side, module, TABLES) # type: ignore[arg-type]
+
+ def sent(self) -> List[bytes]:
+ return [without_sequence(m) for t in self.usb.transfers for m in split(t)]
+
+ async def test_move_parameters_default_to_the_axis_maximum(self) -> None:
+ pod = await self.make_pod("multichannel", "left")
+ self.assertEqual(await pod._unchecked_fw_set_move_parameters([AxisMove("X", 35840)]), [True])
+ # Set X Move Parameters Position:35840, logged in the 2026-10-24 cold start.
+ self.assertEqual(
+ self.sent(), [logged("110100A340807D020000FC03000088130000000000008C00000000")]
+ )
+
+ async def test_move_parameters_with_force_and_explicit_speeds(self) -> None:
+ """A grip at force 5.000 and a tip-loading Z move at 787.500, both logged in the 2026-10-08
+ method run."""
+ span8 = await self.make_pod("span8", "right")
+ await span8._unchecked_fw_set_move_parameters([AxisMove("GG", 34873, force=5000)])
+ self.assertEqual(
+ self.sent(), [logged("111300F54019660100F9F91B00BAC3170188130000398800000000")]
+ )
+
+ left = await self.make_pod("multichannel", "left")
+ await left._unchecked_fw_set_move_parameters(
+ [AxisMove("Z", -35182, velocity=2432, acceleration=12800, jerk=69869, force=787500)]
+ )
+ self.assertEqual(
+ self.sent(), [logged("1103005F408009000000320000ED1001002C040C009276FFFF0000")]
+ )
+
+ async def test_targets_outside_the_limits_send_nothing(self) -> None:
+ pod = await self.make_pod("multichannel", "left")
+ with self.assertRaisesRegex(ValueError, "outside"):
+ await pod._unchecked_fw_set_move_parameters([AxisMove("Y", 0), AxisMove("X", 350721)])
+ self.assertEqual(self.usb.transfers, [])
+
+ async def test_a_pump_whose_valve_is_not_set_is_refused(self) -> None:
+ pod = await self.make_pod("span8", "right")
+ with self.assertRaisesRegex(RuntimeError, "valve"):
+ await pod._unchecked_fw_set_move_parameters([AxisMove("D1", 0)])
+ self.assertEqual(self.usb.transfers, [])
+
+ async def test_not_homed_is_an_answer_and_other_refusals_raise(self) -> None:
+ pod = await self.make_pod("span8", "right")
+ self.usb.handler = lambda m: [m[:5] + b"\x00\x32"] if m[1] == 0x0A else [done(m)]
+ accepted_ = await pod._unchecked_fw_set_move_parameters(
+ [AxisMove("Z1", 9647), AxisMove("Z2", 9647)]
+ )
+ self.assertEqual(accepted_, [False, True])
+ self.usb.handler = lambda m: [m[:5] + b"\x00\x0f"]
+ with self.assertRaises(InterlockTrippedError):
+ await pod._unchecked_fw_set_move_parameters([AxisMove("X", -2560)])
+
+ async def test_a_batch_travels_together(self) -> None:
+ pod = await self.make_pod("span8", "right")
+ await pod._unchecked_fw_set_move_parameters([AxisMove(f"Z{i}", 9647) for i in range(1, 9)])
+ self.assertEqual(len(self.usb.transfers), 1)
+ self.assertEqual([m[1] for m in self.sent()], list(range(0x0A, 0x12)))
+
+ async def test_move_and_move_all(self) -> None:
+ pod = await self.make_pod("multichannel", "left")
+ await pod._unchecked_fw_move("GG")
+ await pod._unchecked_fw_move_all()
+ # Move GG Timeout:30000 and Move All Timeout:5000, as logged.
+ self.assertEqual(self.sent(), [logged("1106007F5030750000"), logged("1000002E5088130000")])
+
+ async def test_home_waits_for_every_axis(self) -> None:
+ pod = await self.make_pod("span8", "right")
+ held: List[bytes] = []
+ self.usb.handler = recorder(held, lambda m: [accepted(m)])
+ task = asyncio.create_task(pod._unchecked_fw_home(["Z1", "Z5"]))
+ while len(held) < 2:
+ await asyncio.sleep(0)
+ self.assertEqual(len(self.usb.transfers), 1) # both homes start together
+ self.usb.push(done(held[0]))
+ await asyncio.sleep(0.05)
+ self.assertFalse(task.done())
+ self.usb.push(done(held[1]))
+ await task
+ self.assertEqual(
+ [without_sequence(m) for m in held], [logged("110A001051"), logged("110E001151")]
+ )
+
+ async def test_enable_addresses_pumps_and_motors(self) -> None:
+ pod = await self.make_pod("span8", "right")
+ await pod._unchecked_fw_enable(["D8", "GY"])
+ await pod._unchecked_fw_stop_motion()
+ self.assertEqual(
+ self.sent(),
+ [logged("1208006B1200"), logged("1112006C1200"), logged("100000670F")],
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/protocol.py b/pylabrobot/beckman_coulter/biomek_i7/driver/protocol.py
new file mode 100644
index 00000000000..63b78df4497
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/protocol.py
@@ -0,0 +1,711 @@
+"""ACE messages: what the Biomek i7's boards are sent and what they answer.
+
+A request is a 5-byte header and its parameters, little-endian::
+
+ device (1) | index (1) | 0x00 | sequence (1) | opcode (1) | parameters
+
+`device` names the kind of thing addressed on the board (the module itself, one of its boards, a
+motor, a syringe pump, an input...), `index` which one of them, and `opcode` the operation, whose
+meaning depends on `device`. A board answers with the same header, then a status byte and the
+status's data::
+
+ device | index | 0x00 | sequence | opcode | status (1) | data
+
+A command that starts something answers twice, ACCEPTED and then DONE; anything else answers
+DONE once. Boards also send messages nobody asked for, with sequence 0: EVENT (an input changed,
+the interlock tripped), NOTICE (the host-alive heartbeat, a move stopped by the interlock) and
+EMERGENCY (CANopen EMCY from a drive, SAGIAN CAN traffic).
+
+The requests here are the ones the Master Controller was logged sending, plus the reads in
+`FIRMWARE_READS`, and nothing else: `Request` refuses any device/opcode pair not in `COMMANDS`,
+so firmware upgrade and flash commands cannot be sent through this module. A firmware read is one the Master Controller never sends, which only reads a state and changes
+nothing.
+"""
+
+import enum
+import struct
+from dataclasses import dataclass, field
+from typing import Dict, List, Literal, Optional, Tuple
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import INTERLOCK_TRIPPED_CODE, ace_error
+
+
+class Device(enum.IntEnum):
+ """The device byte: what kind of thing on a board a message addresses."""
+
+ MODULE = 0x00
+ INTERLOCK = 0x01
+ BOARD = 0x02
+ MOTION_SERVICE = 0x10
+ MOTOR = 0x11
+ PUMP = 0x12
+ TIP_SENSOR = 0x13
+ IO_SERVICE = 0x20
+ DIGITAL_INPUT = 0x21
+ ANALOG_INPUT = 0x22
+ DIGITAL_OUTPUT = 0x28
+ STATUS_DISPLAY = 0x2D
+ ACCUFRAME = 0xAF
+ LEGACY_ALP = 0xFE
+ IO_BOX = 0xFF
+
+
+class Status(enum.IntEnum):
+ """A reply's status byte."""
+
+ ERROR = 0x00
+ ACCEPTED = 0x01
+ DONE = 0x02
+ EVENT = 0x03
+ NOTICE = 0xFE
+ EMERGENCY = 0xFF
+
+
+# Every request this driver may send, by (device, opcode). The names are the Master Controller's.
+COMMANDS: Dict[Tuple[int, int], str] = {
+ (Device.MODULE, 0x00): "Get Module ID",
+ (Device.MODULE, 0x02): "Get Module Serial Number",
+ (Device.MODULE, 0x03): "Get Module Hardware Version",
+ (Device.MODULE, 0x08): "Get Module Device Count",
+ (Device.MODULE, 0x0F): "Stop Module Execution",
+ (Device.MODULE, 0x11): "Get Module Application Image Length",
+ (Device.MODULE, 0x12): "Get Module Application Image CRC",
+ (Device.BOARD, 0x02): "Get Board Serial Number",
+ (Device.BOARD, 0x03): "Get Board Hardware Version",
+ (Device.BOARD, 0x04): "Get Board Bootloader Version",
+ (Device.BOARD, 0x10): "Get Board Application Version",
+ (Device.BOARD, 0x11): "Get Board Application Image Length",
+ (Device.BOARD, 0x12): "Get Board Application Image CRC",
+ (Device.INTERLOCK, 0x11): "Notify On Interlock Trip",
+ (Device.INTERLOCK, 0x50): "Trip Interlock",
+ (Device.INTERLOCK, 0x51): "Re-Arm Interlock",
+ (Device.MOTION_SERVICE, 0x0F): "Stop Motion Service",
+ (Device.MOTION_SERVICE, 0x50): "Move All",
+ (Device.MOTOR, 0x10): "Configure",
+ (Device.MOTOR, 0x12): "Set State",
+ (Device.MOTOR, 0x21): "Get Homed State",
+ (Device.MOTOR, 0x24): "Get Current Position",
+ (Device.MOTOR, 0x31): "Get Control Effort",
+ (Device.MOTOR, 0x40): "Set Move Parameters",
+ (Device.MOTOR, 0x50): "Move",
+ (Device.MOTOR, 0x51): "Home",
+ (Device.PUMP, 0x10): "Configure",
+ (Device.PUMP, 0x12): "Set State",
+ (Device.PUMP, 0x21): "Get Homed State",
+ (Device.PUMP, 0x24): "Get Current Position",
+ (Device.PUMP, 0x40): "Set Move Parameters",
+ (Device.PUMP, 0x51): "Home",
+ (Device.TIP_SENSOR, 0x10): "Get Tip Status",
+ (Device.TIP_SENSOR, 0x41): "Set LLS/CD Sensitivity",
+ (Device.IO_SERVICE, 0x08): "Get IO Service Device Count",
+ (Device.DIGITAL_INPUT, 0x01): "Get Digital Input Name",
+ (Device.DIGITAL_INPUT, 0x10): "Read Digital Input",
+ (Device.DIGITAL_INPUT, 0x11): "Notify On Digital Input Change",
+ (Device.ANALOG_INPUT, 0x01): "Get Analog Input Name",
+ (Device.ANALOG_INPUT, 0x10): "Read Analog Input",
+ (Device.ANALOG_INPUT, 0x12): "Get Analog Input Units",
+ (Device.DIGITAL_OUTPUT, 0x01): "Get Digital Output Name",
+ (Device.DIGITAL_OUTPUT, 0x10): "Read Digital Output",
+ (Device.DIGITAL_OUTPUT, 0x11): "Notify On Digital Output Change",
+ (Device.STATUS_DISPLAY, 0x10): "Set Status Display",
+ (Device.ACCUFRAME, 0xF7): "Get AccuFrame Offsets",
+ (Device.LEGACY_ALP, 0x18): "List Legacy ALP Devices",
+ (Device.IO_BOX, 0x10): "Send Digital I/O Box",
+}
+
+# Reads the Master Controller never sends. Get State answers an axis's state byte (`AxisState`)
+# with no precondition, and changes nothing. Get Interlock Status answers the interlock's state
+# byte; the Master Controller's log names it "Get Interlock Status".
+FIRMWARE_READS: Dict[Tuple[int, int], str] = {
+ (Device.MOTOR, 0x11): "Get State",
+ (Device.PUMP, 0x11): "Get State",
+ (Device.INTERLOCK, 0x10): "Get Interlock Status",
+}
+COMMANDS.update(FIRMWARE_READS)
+
+# Requests that answer ACCEPTED before DONE.
+TWO_STAGE: frozenset = frozenset(
+ {(Device.MOTION_SERVICE, 0x50), (Device.MOTOR, 0x50), (Device.MOTOR, 0x51), (Device.PUMP, 0x51)}
+)
+
+# The opcode a board's unsolicited messages carry, by (device, opcode).
+HOST_ALIVE = (Device.MODULE, 0x40)
+EMCY = (Device.MODULE, 0x31)
+SAGIAN_CAN = (Device.MODULE, 0x30)
+INTERLOCK_TRIPPED = (Device.INTERLOCK, 0x10)
+DIGITAL_INPUT_VALUE = (Device.DIGITAL_INPUT, 0x10)
+
+# A SAGIAN CAN message a Span-8 board passes up: the message's kind and status bytes, named as the
+# Master Controller's log names them ("SAGIAN CAN TO_NODE 05:00 READ SUCCESS F7 ..."). The board
+# shares the CAN bus with the SAGIAN devices behind it (the AccuFrame is node 05) and forwards what
+# it sees there, the answers to the host's own requests included: reading the AccuFrame's offsets
+# through the Multichannel's board brings the AccuFrame's answer back from the Span-8's as well.
+# Every such message in the Master Controller's logs (2026-07-27 .. 10-27) is a success or a
+# request; any other status is not known to be harmless.
+SAGIAN_CAN_KINDS = {0x00: "ACTION", 0x01: "READ", 0x02: "WRITE", 0x03: "EVENT"}
+SAGIAN_CAN_KNOWN_STATUSES = {0x00: "REQUEST", 0x01: "SUCCESS"}
+
+
+def describe_sagian_can(data: bytes) -> Tuple[str, bool]:
+ """A forwarded SAGIAN CAN message as the Master Controller's log words it
+ (`TO_NODE 05:00 READ SUCCESS F7 28 0F BB 40`), and whether its status is one of those seen in
+ normal operation (`SAGIAN_CAN_KNOWN_STATUSES`)."""
+ if len(data) < 7:
+ return f"short message {data.hex()}", False
+ kind = SAGIAN_CAN_KINDS.get(data[5], f"kind 0x{data[5]:02X}")
+ status = SAGIAN_CAN_KNOWN_STATUSES.get(data[6])
+ words = [
+ "TO_NODE" if data[1] == 0x01 else f"direction 0x{data[1]:02X}",
+ f"{data[2]:02X}:{data[4]:02X}",
+ kind,
+ status or f"status 0x{data[6]:02X}",
+ ]
+ if len(data) > 7:
+ words.append(data[7:].hex(" ").upper())
+ return " ".join(words), status is not None and data[1] == 0x01
+
+
+# A drive's own error code while its motor power is off, the interlock tripped ("interlock active").
+INTERLOCK_ACTIVE = 0x0416
+
+
+def describe_routine_unsolicited(reply: "Reply") -> Optional[str]:
+ """What an unsolicited message every session sees says, or None for one worth showing.
+
+ Routine: a drive's EMCY with error 0000 (its fault cleared, as it is enabled), a drive's EMCY
+ naming `interlock active`, and a Move All notice ending in `interlock tripped`. The last two
+ follow every interlock trip, the driver's own at `stop` included. So does the chassis's trip event
+ (Notify On Interlock Trip), which is logged at INFO; `BiomekI7Driver` tells a trip it made from
+ one it did not."""
+ if (reply.device, reply.opcode) == EMCY and reply.status == Status.EMERGENCY:
+ if len(reply.data) < 8:
+ return None
+ emcy = parse_emcy(reply.data)
+ if emcy.error_code == 0:
+ return f"drive node 0x{emcy.node:02X}: fault cleared (EMCY 0000)"
+ if emcy.device_error == INTERLOCK_ACTIVE:
+ return f"drive node 0x{emcy.node:02X}: interlock active (EMCY {emcy.error_code:04X})"
+ return None
+ if reply.status == Status.NOTICE and reply.error_code == INTERLOCK_TRIPPED_CODE:
+ return f"device 0x{reply.device:02X} index {reply.index}: move ended, interlock tripped"
+ return None
+
+
+@dataclass(frozen=True)
+class Request:
+ """One request, before a sequence number is given to it."""
+
+ device: int
+ index: int
+ opcode: int
+ params: bytes = b""
+
+ def __post_init__(self) -> None:
+ if (self.device, self.opcode) not in COMMANDS:
+ raise ValueError(
+ f"device 0x{self.device:02X} opcode 0x{self.opcode:02X} is not a command this driver sends"
+ )
+ if not 0 <= self.index <= 0xFF:
+ raise ValueError(f"index must be 0-255, got {self.index}")
+
+ @property
+ def name(self) -> str:
+ return COMMANDS[(self.device, self.opcode)]
+
+ @property
+ def two_stage(self) -> bool:
+ """Whether the board answers ACCEPTED before DONE."""
+ return (self.device, self.opcode) in TWO_STAGE
+
+ def encode(self, sequence: int) -> bytes:
+ """The message bytes, with `sequence` (1-255; 0 is the boards' own)."""
+ if not 1 <= sequence <= 0xFF:
+ raise ValueError(f"sequence must be 1-255, got {sequence}")
+ return bytes([self.device, self.index, 0x00, sequence, self.opcode]) + self.params
+
+ def __str__(self) -> str:
+ return f"{self.name} (device 0x{self.device:02X}, index {self.index})"
+
+
+@dataclass(frozen=True)
+class Reply:
+ """One message from a board."""
+
+ device: int
+ index: int
+ sequence: int
+ opcode: int
+ status: int
+ data: bytes
+ # Replies the board sent under this request's sequence for other devices: a Move All's axes
+ # report there when they end other than plainly. Set by `AceBoard` on the final reply.
+ related: Tuple["Reply", ...] = field(default=(), compare=False)
+
+ @classmethod
+ def parse(cls, message: bytes) -> "Reply":
+ """Split a message into its header, status and data.
+
+ Raises:
+ ValueError: if the message is shorter than a header and a status byte.
+ """
+ if len(message) < 6:
+ raise ValueError(f"ACE reply too short: {message.hex()}")
+ device, index, _, sequence, opcode, status = message[:6]
+ return cls(device, index, sequence, opcode, status, bytes(message[6:]))
+
+ @property
+ def key(self) -> Tuple[int, int, int, int]:
+ """What a reply shares with the request it answers."""
+ return (self.device, self.index, self.sequence, self.opcode)
+
+ @property
+ def unsolicited(self) -> bool:
+ return self.sequence == 0
+
+ @property
+ def error_code(self) -> Optional[int]:
+ """The ACE error code, or None when the reply reports success."""
+ if self.status == Status.ERROR:
+ return self.data[0] if self.data else 0
+ if self.status in (Status.ACCEPTED, Status.DONE, Status.NOTICE) and self.data and self.data[0]:
+ return self.data[0]
+ return None
+
+ @property
+ def device_error(self) -> Optional[int]:
+ """The drive's own error code that follows the ACE error code, when there is one."""
+ if self.error_code is None or len(self.data) < 2:
+ return None
+ return int.from_bytes(self.data[1:], "little")
+
+ @property
+ def payload(self) -> bytes:
+ """What a successful reply returns, after its zero error byte."""
+ return self.data[1:]
+
+ def raise_for_error(self, request: str) -> None:
+ """Raise the `AceError` this reply reports, if it reports one."""
+ code = self.error_code
+ if code is not None:
+ raise ace_error(code, self.device_error, request, self.device, self.index)
+
+ def check(self, request: str) -> "Reply":
+ """Return this reply, or raise the `AceError` it reports."""
+ self.raise_for_error(request)
+ return self
+
+
+# -- requests ----------------------------------------------------------------
+
+
+def get_module_id() -> Request:
+ return Request(Device.MODULE, 0, 0x00)
+
+
+def get_module_serial_number() -> Request:
+ return Request(Device.MODULE, 0, 0x02)
+
+
+def get_module_hardware_version() -> Request:
+ return Request(Device.MODULE, 0, 0x03)
+
+
+def get_module_device_count() -> Request:
+ return Request(Device.MODULE, 0, 0x08)
+
+
+def get_module_application_image_length() -> Request:
+ return Request(Device.MODULE, 0, 0x11)
+
+
+def get_module_application_image_crc() -> Request:
+ return Request(Device.MODULE, 0, 0x12)
+
+
+def stop_module_execution() -> Request:
+ return Request(Device.MODULE, 0, 0x0F)
+
+
+def get_board_serial_number(board: int) -> Request:
+ return Request(Device.BOARD, board, 0x02)
+
+
+def get_board_hardware_version(board: int) -> Request:
+ return Request(Device.BOARD, board, 0x03)
+
+
+def get_board_bootloader_version(board: int) -> Request:
+ return Request(Device.BOARD, board, 0x04)
+
+
+def get_board_application_version(board: int) -> Request:
+ return Request(Device.BOARD, board, 0x10)
+
+
+def get_board_application_image_length(board: int) -> Request:
+ return Request(Device.BOARD, board, 0x11)
+
+
+def get_board_application_image_crc(board: int) -> Request:
+ return Request(Device.BOARD, board, 0x12)
+
+
+def get_interlock_status(interlock: int = 1) -> Request:
+ return Request(Device.INTERLOCK, interlock, 0x10)
+
+
+def notify_on_interlock_trip(interlock: int = 1, notify: bool = True) -> Request:
+ return Request(Device.INTERLOCK, interlock, 0x11, bytes([int(notify)]))
+
+
+def trip_interlock(interlock: int = 1) -> Request:
+ return Request(Device.INTERLOCK, interlock, 0x50)
+
+
+def rearm_interlock(interlock: int = 1) -> Request:
+ return Request(Device.INTERLOCK, interlock, 0x51)
+
+
+def stop_motion_service() -> Request:
+ return Request(Device.MOTION_SERVICE, 0, 0x0F)
+
+
+def move_all(timeout_ms: int) -> Request:
+ """Start every move whose parameters were set since the last move, together."""
+ return Request(Device.MOTION_SERVICE, 0, 0x50, struct.pack(" Request:
+ """Load an axis's motor table. `payload` is the table exactly as the Master Controller sent it."""
+ return Request(device, axis, 0x10, payload)
+
+
+def set_state_enabled(device: int, axis: int) -> Request:
+ return Request(device, axis, 0x12, b"\x00")
+
+
+def get_state(device: int, axis: int) -> Request:
+ """Ask a motor or pump for its state byte; see `AxisState`."""
+ return Request(device, axis, 0x11)
+
+
+def get_homed_state(device: int, axis: int) -> Request:
+ """Whether a motor or a pump (`device`) has been homed since the board started."""
+ return Request(device, axis, 0x21)
+
+
+def get_current_position(device: int, axis: int) -> Request:
+ return Request(device, axis, 0x24)
+
+
+def get_control_effort(axis: int) -> Request:
+ return Request(Device.MOTOR, axis, 0x31)
+
+
+# The largest force limit Set Move Parameters can carry: a u32 of the Master Controller's units x1000.
+MAX_FORCE = 4294967.295
+
+
+def set_motor_move_parameters(
+ axis: int,
+ position: int,
+ velocity: int,
+ acceleration: int,
+ jerk: int,
+ force: int = 0,
+ sensor: int = 0,
+ trigger: int = 0,
+) -> Request:
+ """Set a motor's next move, in counts, laid out as the Master Controller's logged requests lay
+ it out. `force` is the force limit x1000 (grip and tip loading), 0 for none. `sensor`
+ and `trigger` make the move stop where a sensor fires: liquid-level sensing on a Span-8 Z, the
+ AccuFrame when framing (0, 0: no sensor)."""
+ params = struct.pack(" Request:
+ """Set a syringe pump's next move, in counts, with the valve position it moves through."""
+ params = struct.pack(
+ " Request:
+ """Start one motor's move on its own."""
+ return Request(Device.MOTOR, axis, 0x50, struct.pack(" Request:
+ return Request(device, axis, 0x51)
+
+
+def get_tip_status(sensor: int = 1) -> Request:
+ return Request(Device.TIP_SENSOR, sensor, 0x10)
+
+
+def set_lls_cd_sensitivity(clot_detection: bool, value: int) -> Request:
+ """Liquid-level (or, with `clot_detection`, clot-detection) sensitivity, 0-4095, on the Span-8's
+ LLS/CD board (the device that also answers Get Tip Status): what the Master Controller sends
+ for `SS`."""
+ if not 0 <= value <= 4095:
+ raise ValueError(f"sensitivity {value} is outside 0..4095")
+ return Request(Device.TIP_SENSOR, 1, 0x41, struct.pack(" Request:
+ return Request(Device.IO_SERVICE, 0, 0x08)
+
+
+def get_input_output_name(device: int, index: int) -> Request:
+ return Request(device, index, 0x01)
+
+
+def read_input_output(device: int, index: int) -> Request:
+ return Request(device, index, 0x10)
+
+
+def notify_on_change(device: int, index: int, notify: bool = True) -> Request:
+ return Request(device, index, 0x11, bytes([int(notify)]))
+
+
+def get_analog_input_units(index: int) -> Request:
+ return Request(Device.ANALOG_INPUT, index, 0x12)
+
+
+# ERROR is what the Master Controller shows after a failed move (2026-07-31, `2D 01 00 seq 10 05`).
+StatusDisplayState = Literal["ready", "running", "paused", "error"]
+STATUS_DISPLAY_STATES = {"ready": 0x02, "running": 0x03, "paused": 0x04, "error": 0x05}
+
+
+def set_status_display(state: StatusDisplayState, display: int = 1) -> Request:
+ return Request(Device.STATUS_DISPLAY, display, 0x10, bytes([STATUS_DISPLAY_STATES[state]]))
+
+
+def get_accuframe_offsets(accuframe: int = 1) -> Request:
+ return Request(Device.ACCUFRAME, accuframe, 0xF7)
+
+
+def list_legacy_alp_devices() -> Request:
+ return Request(Device.LEGACY_ALP, 0, 0x18)
+
+
+def send_digital_io_box(params: bytes, box: int = 1) -> Request:
+ """Pass a command to the digital I/O box. Its bytes are the box's own and are not decoded here."""
+ return Request(Device.IO_BOX, box, 0x10, params)
+
+
+# -- replies -----------------------------------------------------------------
+
+# Get Module ID's two bytes, as the Master Controller's log decodes them ("Chassis", "Left
+# Multichannel", "Right Span-8"). Only these three were seen, on one instrument.
+MODULE_TYPES = {0x80: "chassis", 0xFD: "multichannel", 0xFB: "span8"}
+MODULE_SIDES = {0x00: None, 0x01: "left", 0x02: "right"}
+
+# Hardware version type codes, as the Master Controller names them.
+HARDWARE_NAMES = {
+ 0x00: "Motion Board",
+ 0x01: "Transport Supervisor",
+ 0x02: "Chassis Supervisor",
+ 0xE0: "SAGIAN Motion Board",
+ 0xE1: "SAGIAN LLS Board",
+ 0xE2: "SAGIAN Syringe Pump Board",
+ 0xE3: "AccuFrame",
+ 0xE5: "Device Controller",
+}
+
+# Tip sensor codes. 1 is "cannot determine" in the Master Controller's `VT` replies.
+TIP_STATES = {0x00: "loaded", 0x01: "unknown", 0x02: "unloaded"}
+
+# What an axis reports when its part of a Move All ends other than plainly. A 1-byte report is
+# one of the statuses; a 5-byte report is a type and the s32 position where its sensor fired.
+LLS_LIQUID_SENSED = 69
+LLS_LIQUID_NOT_SENSED = 70
+CD_CLOT_NOT_DETECTED = 71
+CD_CLOT_DETECTED = 72
+ACCUFRAME = 175
+MotionOutcome = Literal[
+ "done", "liquid-sensed", "accuframe", "liquid-not-sensed", "clot-not-detected", "clot-detected"
+]
+MOTION_OUTCOMES: Dict[int, MotionOutcome] = {
+ LLS_LIQUID_SENSED: "liquid-sensed",
+ LLS_LIQUID_NOT_SENSED: "liquid-not-sensed",
+ CD_CLOT_NOT_DETECTED: "clot-not-detected",
+ CD_CLOT_DETECTED: "clot-detected",
+ ACCUFRAME: "accuframe",
+}
+
+
+class AxisState(enum.IntEnum):
+ """A motor's or pump's state byte, as Get State answers it.
+
+ An axis starts NOT_CONFIGURED at power-up, and goes back to it when Configure starts or a SAGIAN
+ drive reports it lost its parameters. Configure ends DISABLED; Set State moves between DISABLED
+ and ENABLED; Home and moves need ENABLED. FAULT follows a drive error.
+ """
+
+ ENABLED = 0x00
+ DISABLED = 0x01
+ NOT_CONFIGURED = 0xFE
+ FAULT = 0xFF
+
+
+AxisStateName = Literal["enabled", "disabled", "not_configured", "fault"]
+"""An `AxisState` as the public API gives it (`Pod.request_axis_states`): its name, lower case."""
+
+
+@dataclass(frozen=True)
+class ModuleId:
+ """What Get Module ID answers: the kind of module and, for an arm's, its side."""
+
+ type_code: int
+ side_code: int
+
+ @property
+ def type(self) -> Optional[str]:
+ """`chassis`, `multichannel` or `span8`; None for a code not seen yet."""
+ return MODULE_TYPES.get(self.type_code)
+
+ @property
+ def side(self) -> Optional[str]:
+ """`left` or `right` for an arm's module, None for the chassis."""
+ return MODULE_SIDES.get(self.side_code)
+
+
+@dataclass(frozen=True)
+class HardwareVersion:
+ type_code: int
+ revision: int
+
+ @property
+ def name(self) -> str:
+ return HARDWARE_NAMES.get(self.type_code, f"hardware 0x{self.type_code:02X}")
+
+ def __str__(self) -> str:
+ return f"{self.name} {self.revision}"
+
+
+@dataclass(frozen=True)
+class Emcy:
+ """A CANopen emergency message a drive sent through its board."""
+
+ node: int
+ error_code: int
+ error_register: int
+ device_error: int
+ source: int
+
+
+def parse_module_id(payload: bytes) -> ModuleId:
+ return ModuleId(payload[0], payload[1])
+
+
+def parse_string(payload: bytes) -> str:
+ return payload.decode("ascii")
+
+
+def parse_hardware_version(payload: bytes) -> HardwareVersion:
+ return HardwareVersion(payload[0], payload[1])
+
+
+def parse_device_count(payload: bytes) -> Dict[int, int]:
+ """Each kind of device a module or service holds, by device byte, and how many."""
+ if len(payload) % 3:
+ raise ValueError(f"device count is (device, u16 count) triples, got {payload.hex()}")
+ return {
+ payload[i]: int.from_bytes(payload[i + 1 : i + 3], "little") for i in range(0, len(payload), 3)
+ }
+
+
+def parse_u32(payload: bytes) -> int:
+ return int(struct.unpack_from(" int:
+ return int(struct.unpack_from(" float:
+ return float(struct.unpack_from(" Tuple[float, float, float]:
+ x, y, z = struct.unpack_from(" InterlockState:
+ """Raises `ValueError` for a byte not seen."""
+ state = INTERLOCK_STATES.get(payload[0])
+ if state is None:
+ raise ValueError(f"interlock state 0x{payload[0]:02X} has not been seen")
+ return state # type: ignore[return-value]
+
+
+def parse_axis_state(payload: bytes) -> AxisState:
+ """Raises `ValueError` for a state byte the firmware does not set."""
+ return AxisState(payload[0])
+
+
+def parse_tip_status(payload: bytes) -> List[Optional[str]]:
+ """Each channel's tip, `loaded` or `unloaded`; None for a code not seen yet."""
+ return [TIP_STATES.get(b) for b in payload]
+
+
+@dataclass(frozen=True)
+class MotionComplete:
+ """How one axis's part of a Move All ended: `done`, or a sensor outcome; `position` is where a
+ sensor stopped it (liquid sensed, AccuFrame), else None."""
+
+ device: int
+ index: int
+ outcome: MotionOutcome
+ position: Optional[int] = None
+
+
+def parse_motion_complete(reply: Reply) -> MotionComplete:
+ """An axis's report inside a Move All."""
+ payload = reply.payload
+ if len(payload) == 5:
+ (position,) = struct.unpack_from(" Emcy:
+ """Decode an EMERGENCY reply's data: node, CANopen error code and register, then the drive's own
+ error code and the source it names."""
+ node = data[1]
+ error_code, error_register, device_error, source = struct.unpack_from(" (the request, its sequence, the frame's bytes, what the log says it is).
+# The reads the Master Controller never sends (`FIRMWARE_READS`) were never logged; their frames
+# follow the request layout.
+FRAMES: Dict[Tuple[int, int], Tuple[Callable[[], p.Request], int, str, str]] = {
+ (0x00, 0x00): (p.get_module_id, 0x01, "0000000100", "Get Module ID"),
+ (0x00, 0x02): (p.get_module_serial_number, 0x03, "0000000302", "Get Module Serial Number"),
+ (0x00, 0x03): (p.get_module_hardware_version, 0x02, "0000000203", "Get Module Hardware Version"),
+ (0x00, 0x08): (p.get_module_device_count, 0x06, "0000000608", "Get Module Device Count"),
+ (0x00, 0x0F): (p.stop_module_execution, 0x75, "000000750F", "Stop Module Execution"),
+ (0x00, 0x11): (
+ p.get_module_application_image_length,
+ 0x05,
+ "0000000511",
+ "Get Module Application Image Length",
+ ),
+ (0x00, 0x12): (
+ p.get_module_application_image_crc,
+ 0x04,
+ "0000000412",
+ "Get Module Application Image CRC",
+ ),
+ (0x02, 0x02): (
+ lambda: p.get_board_serial_number(6),
+ 0x0B,
+ "0206000B02",
+ "Get Board 6 Serial Number",
+ ),
+ (0x02, 0x03): (
+ lambda: p.get_board_hardware_version(1),
+ 0x07,
+ "0201000703",
+ "Get Board 1 Hardware Version",
+ ),
+ (0x02, 0x04): (
+ lambda: p.get_board_bootloader_version(7),
+ 0x31,
+ "0207003104",
+ "Get Board 7 Bootloader Version",
+ ),
+ (0x02, 0x10): (
+ lambda: p.get_board_application_version(1),
+ 0x08,
+ "0201000810",
+ "Get Board 1 Application Version",
+ ),
+ (0x02, 0x11): (
+ lambda: p.get_board_application_image_length(6),
+ 0x0D,
+ "0206000D11",
+ "Get Board 6 Application Image Length",
+ ),
+ (0x02, 0x12): (
+ lambda: p.get_board_application_image_crc(6),
+ 0x0C,
+ "0206000C12",
+ "Get Board 6 Application Image CRC",
+ ),
+ (0x01, 0x10): (p.get_interlock_status, 0x09, "0101000910", "(never logged)"),
+ (0x01, 0x11): (p.notify_on_interlock_trip, 0x28, "010100281101", "Notify On Interlock Trip TRUE"),
+ (0x01, 0x50): (p.trip_interlock, 0xEA, "010100EA50", "Trip Interlock"),
+ (0x01, 0x51): (p.rearm_interlock, 0xE1, "010100E151", "Re-Arm Interlock"),
+ (0x10, 0x0F): (p.stop_motion_service, 0x67, "100000670F", "Stop Motion Service"),
+ (0x10, 0x50): (lambda: p.move_all(5000), 0x28, "100000285088130000", "Move All Timeout:5000"),
+ (0x11, 0x10): (
+ lambda: p.configure(p.Device.MOTOR, 2, MOTOR_TABLE),
+ 0x2F,
+ "1102002F10" + MOTOR_TABLE.hex(),
+ "Configure Y1 Minimum Velocity:23 ...",
+ ),
+ (0x11, 0x11): (lambda: p.get_state(p.Device.MOTOR, 3), 0x07, "1103000711", "(never logged)"),
+ (0x11, 0x12): (
+ lambda: p.set_state_enabled(p.Device.MOTOR, 3),
+ 0x76,
+ "110300761200",
+ "Set Z State ENABLED",
+ ),
+ (0x11, 0x21): (
+ lambda: p.get_homed_state(p.Device.MOTOR, 1),
+ 0x3C,
+ "1101003C21",
+ "Get X Homed State",
+ ),
+ (0x11, 0x24): (
+ lambda: p.get_current_position(p.Device.MOTOR, 7),
+ 0x80,
+ "1107008024",
+ "Get GZ Current Position",
+ ),
+ (0x11, 0x31): (lambda: p.get_control_effort(0x13), 0x96, "1113009631", "Get GG Control Effort"),
+ (0x11, 0x40): (
+ lambda: p.set_motor_move_parameters(
+ 3, position=-1000, velocity=24320, acceleration=128000, jerk=698880
+ ),
+ 0xAB,
+ "110300AB40005F000000F4010000AA0A000000000018FCFFFF0000",
+ "Set Z Move Parameters Position:-1000 Velocity:24320 Acceleration:128000 Jerk:698880",
+ ),
+ (0x11, 0x50): (lambda: p.move(3, 30000), 0xAC, "110300AC5030750000", "Move Z Timeout:30000"),
+ (0x11, 0x51): (lambda: p.home(p.Device.MOTOR, 3), 0xAD, "110300AD51", "Home Z"),
+ (0x12, 0x10): (
+ lambda: p.configure(p.Device.PUMP, 1, PUMP_TABLE),
+ 0x3F,
+ "1201003F10" + PUMP_TABLE.hex(),
+ "Configure D1 Minimum Start Velocity:200 ...",
+ ),
+ (0x12, 0x11): (lambda: p.get_state(p.Device.PUMP, 1), 0x07, "1201000711", "(never logged)"),
+ (0x12, 0x12): (
+ lambda: p.set_state_enabled(p.Device.PUMP, 8),
+ 0x6B,
+ "1208006B1200",
+ "Set D8 State ENABLED",
+ ),
+ (0x12, 0x21): (
+ lambda: p.get_homed_state(p.Device.PUMP, 1),
+ 0xDB,
+ "120100DB21",
+ "Get D1 Homed State",
+ ),
+ (0x12, 0x24): (
+ lambda: p.get_current_position(p.Device.PUMP, 8),
+ 0x88,
+ "1208008824",
+ "Get D8 Current Position",
+ ),
+ (0x12, 0x40): (
+ lambda: p.set_pump_move_parameters(
+ 2,
+ position=0,
+ start_velocity=200,
+ max_velocity=23200,
+ cutoff_velocity=200,
+ acceleration=50000,
+ valve="input",
+ ),
+ 0x72,
+ "1202007240C8000000A05A0000C800000050C300000000000000",
+ "Set D2 Move Parameters Position:0 Valve:INPUT Start Velocity:200 Maximum Velocity:23200 "
+ "Cutoff Velocity:200 Acceleration:50000",
+ ),
+ (0x12, 0x51): (lambda: p.home(p.Device.PUMP, 1), 0x60, "1201006051", "Home D1"),
+ (0x13, 0x10): (p.get_tip_status, 0x95, "1301009510", "Get Tip Status"),
+ (0x13, 0x41): (
+ lambda: p.set_lls_cd_sensitivity(False, 3500),
+ 0xA2,
+ "130100A24100AC0D",
+ "Set LLS Sensitivity 3500",
+ ),
+ (0x20, 0x08): (p.get_io_service_device_count, 0x0A, "2000000A08", "Get IO Service Device Count"),
+ (0x21, 0x01): (
+ lambda: p.get_input_output_name(p.Device.DIGITAL_INPUT, 1),
+ 0x1E,
+ "2101001E01",
+ "Get Digital Input 1 Name",
+ ),
+ (0x21, 0x10): (
+ lambda: p.read_input_output(p.Device.DIGITAL_INPUT, 1),
+ 0x20,
+ "2101002010",
+ "Read Digital Input 1",
+ ),
+ (0x21, 0x11): (
+ lambda: p.notify_on_change(p.Device.DIGITAL_INPUT, 1),
+ 0x1F,
+ "2101001F1101",
+ "Notify On Digital Input 1 Change TRUE",
+ ),
+ (0x22, 0x01): (
+ lambda: p.get_input_output_name(p.Device.ANALOG_INPUT, 9),
+ 0x0B,
+ "2209000B01",
+ "Get Analog Input 9 Name",
+ ),
+ (0x22, 0x10): (
+ lambda: p.read_input_output(p.Device.ANALOG_INPUT, 1),
+ 0x65,
+ "2201006510",
+ "Read Analog Input 1",
+ ),
+ (0x22, 0x12): (
+ lambda: p.get_analog_input_units(9),
+ 0x0C,
+ "2209000C12",
+ "Get Analog Input 9 Units",
+ ),
+ (0x28, 0x01): (
+ lambda: p.get_input_output_name(p.Device.DIGITAL_OUTPUT, 1),
+ 0x22,
+ "2801002201",
+ "Get Digital Output 1 Name",
+ ),
+ (0x28, 0x10): (
+ lambda: p.read_input_output(p.Device.DIGITAL_OUTPUT, 1),
+ 0x24,
+ "2801002410",
+ "Read Digital Output 1",
+ ),
+ (0x28, 0x11): (
+ lambda: p.notify_on_change(p.Device.DIGITAL_OUTPUT, 1),
+ 0x23,
+ "280100231101",
+ "Notify On Digital Output 1 Change TRUE",
+ ),
+ (0x2D, 0x10): (
+ lambda: p.set_status_display("running"),
+ 0xE2,
+ "2D0100E21003",
+ "Set Status Display RUNNING",
+ ),
+ (0xAF, 0xF7): (p.get_accuframe_offsets, 0x32, "AF010032F7", "Get AccuFrame Offsets"),
+ (0xFE, 0x18): (p.list_legacy_alp_devices, 0x26, "FE00002618", "List Legacy ALP Devices"),
+ (0xFF, 0x10): (
+ lambda: p.send_digital_io_box(b"\x02\x01"),
+ 0xE0,
+ "FF0100E0100201",
+ "Send Digital I/O Box 00 WRITE 01",
+ ),
+}
+
+
+def decode(message: bytes) -> Tuple[int, int, int, int, bytes]:
+ """A request's header and parameters, by the layout in `protocol.py`'s docstring."""
+ device, index, zero, sequence, opcode = message[:5]
+ assert zero == 0
+ return device, index, sequence, opcode, message[5:]
+
+
+class ExactFrameTests(unittest.TestCase):
+ def test_every_command_has_its_frame(self) -> None:
+ """A command added to `COMMANDS` needs its frame here."""
+ self.assertEqual(set(FRAMES), set(p.COMMANDS))
+
+ def test_each_request_is_the_logged_frame(self) -> None:
+ for key, (build, sequence, frame_hex, logged) in FRAMES.items():
+ with self.subTest(command=p.COMMANDS[key], logged=logged):
+ request = build()
+ self.assertEqual((request.device, request.opcode), key)
+ self.assertEqual(request.encode(sequence), bytes.fromhex(frame_hex))
+
+ def test_reads_never_logged_only_read(self) -> None:
+ for key, name in p.FIRMWARE_READS.items():
+ self.assertTrue(name.startswith("Get "), name)
+ self.assertEqual(p.COMMANDS[key], name)
+
+ def test_status_display_error_is_the_logged_frame(self) -> None:
+ # Log.db3, after a failed move: `2D 01 00 seq 10 05`.
+ self.assertEqual(p.set_status_display("error").encode(0x2E), bytes.fromhex("2D01002E1005"))
+
+ def test_only_moves_and_homes_answer_twice(self) -> None:
+ two_stage = {key for key in FRAMES if FRAMES[key][0]().two_stage}
+ self.assertEqual(two_stage, {(0x10, 0x50), (0x11, 0x50), (0x11, 0x51), (0x12, 0x51)})
+
+
+class RoundTripTests(unittest.TestCase):
+ """Build, then parse: every field comes back out as it went in."""
+
+ def setUp(self) -> None:
+ self.random = random.Random(7)
+
+ def test_header(self) -> None:
+ for key in FRAMES:
+ for _ in range(5):
+ index, sequence = self.random.randrange(256), self.random.randrange(1, 256)
+ params = bytes(self.random.randrange(256) for _ in range(self.random.randrange(4)))
+ message = p.Request(key[0], index, key[1], params).encode(sequence)
+ self.assertEqual(decode(message), (key[0], index, sequence, key[1], params))
+
+ def test_motor_move_parameters(self) -> None:
+ for _ in range(50):
+ values = dict(
+ velocity=self.random.randrange(2**32),
+ acceleration=self.random.randrange(2**32),
+ jerk=self.random.randrange(2**32),
+ force=self.random.randrange(2**32),
+ position=self.random.randrange(-(2**31), 2**31),
+ sensor=self.random.randrange(256),
+ trigger=self.random.randrange(256),
+ )
+ axis = self.random.randrange(1, 32)
+ device, index, _, opcode, params = decode(
+ p.set_motor_move_parameters(axis, **values).encode(1)
+ )
+ self.assertEqual((device, index, opcode), (p.Device.MOTOR, axis, 0x40))
+ fields = struct.unpack(" None:
+ for valve, code in p.VALVE_POSITIONS.items():
+ values = [self.random.randrange(2**32) for _ in range(4)]
+ position = self.random.randrange(-(2**31), 2**31)
+ request = p.set_pump_move_parameters(
+ 3,
+ position,
+ values[0],
+ values[1],
+ values[2],
+ values[3],
+ valve, # type: ignore[arg-type]
+ )
+ _, index, _, opcode, params = decode(request.encode(1))
+ self.assertEqual((request.device, index, opcode), (p.Device.PUMP, 3, 0x40))
+ self.assertEqual(struct.unpack(" None:
+ for timeout in (0, 5000, 30000, 2**32 - 1):
+ self.assertEqual(struct.unpack(" None:
+ for table in (MOTOR_TABLE, PUMP_TABLE):
+ self.assertEqual(decode(p.configure(p.Device.MOTOR, 1, table).encode(1))[4], table)
+
+ def test_lls_cd_sensitivity(self) -> None:
+ for clot in (False, True):
+ for value in (0, 1, 3500, 4095):
+ params = decode(p.set_lls_cd_sensitivity(clot, value).encode(1))[4]
+ self.assertEqual(struct.unpack(" None:
+ for _ in range(50):
+ header = [self.random.randrange(256) for _ in range(5)]
+ header[2] = 0
+ status = self.random.choice(list(p.Status))
+ data = bytes(self.random.randrange(256) for _ in range(self.random.randrange(8)))
+ reply = p.Reply.parse(bytes(header) + bytes([status]) + data)
+ self.assertEqual(
+ (reply.device, reply.index, reply.sequence, reply.opcode, reply.status, reply.data),
+ (header[0], header[1], header[3], header[4], status, data),
+ )
+ self.assertEqual(reply.key, (header[0], header[1], header[3], header[4]))
+ self.assertEqual(reply.unsolicited, header[3] == 0)
+
+ def test_numbers(self) -> None:
+ for _ in range(50):
+ s32 = self.random.randrange(-(2**31), 2**31)
+ u32 = self.random.randrange(2**32)
+ self.assertEqual(p.parse_s32(struct.pack(" None:
+ counts = {0x02: 6, 0x11: 21, 0x12: 8, 0x22: 300}
+ payload = b"".join(bytes([d]) + n.to_bytes(2, "little") for d, n in counts.items())
+ self.assertEqual(p.parse_device_count(payload), counts)
+ with self.assertRaises(ValueError):
+ p.parse_device_count(payload[:-1])
+ version = p.parse_hardware_version(bytes([0xE3, 4]))
+ self.assertEqual((version.type_code, version.revision, str(version)), (0xE3, 4, "AccuFrame 4"))
+ self.assertEqual(str(p.parse_hardware_version(bytes([0x7A, 1]))), "hardware 0x7A 1")
+
+
+class RefusalTests(unittest.TestCase):
+ def test_unknown_commands_are_refused(self) -> None:
+ with self.assertRaises(ValueError):
+ p.Request(p.Device.BOARD, 1, 0x05) # not a logged opcode: other commands stay unsendable
+
+ def test_index_and_sequence_ranges(self) -> None:
+ with self.assertRaises(ValueError):
+ p.Request(p.Device.MOTOR, 256, 0x24)
+ for sequence in (0, 256):
+ with self.assertRaises(ValueError):
+ p.get_module_id().encode(sequence)
+
+
+class ReplyTests(unittest.TestCase):
+ """Replies as the boards send them (the header, status, then data)."""
+
+ def test_module_id(self) -> None:
+ seen: List[Tuple[object, object]] = []
+ for message in ("000000010002008000", "00000001000200FD01", "00000001000200FB02"):
+ module = p.parse_module_id(
+ p.Reply.parse(bytes.fromhex(message)).check("Get Module ID").payload
+ )
+ seen.append((module.type, module.side))
+ self.assertEqual(seen, [("chassis", None), ("multichannel", "left"), ("span8", "right")])
+ unknown = p.parse_module_id(bytes([0x42, 0x07]))
+ self.assertEqual((unknown.type, unknown.side), (None, None))
+
+ def test_strings(self) -> None:
+ reply = p.Reply.parse(bytes.fromhex("0000000302020053494D554C41544544") + b"0" * 4)
+ self.assertEqual(p.parse_string(reply.payload), "SIMULATED0000")
+ reply = p.Reply.parse(bytes.fromhex("02010008100200302E322E34"))
+ self.assertEqual(p.parse_string(reply.payload), "0.2.4")
+
+ def test_interlock_status(self) -> None:
+ self.assertEqual(p.parse_interlock_status(b"\x00"), "armed")
+ self.assertEqual(p.parse_interlock_status(b"\xff"), "tripped")
+ with self.assertRaisesRegex(ValueError, "not been seen"):
+ p.parse_interlock_status(b"\x01")
+ # The unsolicited trip event carries the same byte.
+ event = p.Reply.parse(bytes.fromhex("01010000100300FF"))
+ self.assertEqual((event.device, event.opcode), p.INTERLOCK_TRIPPED)
+ self.assertEqual(p.parse_interlock_status(event.payload), "tripped")
+
+ def test_axis_state(self) -> None:
+ for code, state in [(0x00, "ENABLED"), (0x01, "DISABLED"), (0xFE, "NOT_CONFIGURED"),
+ (0xFF, "FAULT")]: # fmt: skip
+ self.assertEqual(p.parse_axis_state(bytes([code])).name, state)
+ with self.assertRaises(ValueError):
+ p.parse_axis_state(b"\x02")
+
+ def test_tip_status(self) -> None:
+ states = p.parse_tip_status(bytes([0, 2, 1, 2, 0, 0, 2, 9]))
+ self.assertEqual(
+ states, ["loaded", "unloaded", "unknown", "unloaded", "loaded", "loaded", "unloaded", None]
+ )
+
+ def test_motion_complete(self) -> None:
+ sensed = p.Reply.parse(
+ bytes([0x11, 9, 0, 5, 0x50, 0x02, 0, p.LLS_LIQUID_SENSED]) + struct.pack(" None:
+ emcy = p.parse_emcy(bytes.fromhex("007700100116040100"))
+ self.assertEqual(
+ (emcy.node, emcy.error_code, emcy.error_register, emcy.device_error, emcy.source),
+ (0x77, 0x1000, 0x01, 0x0416, 0x01),
+ )
+
+ def test_success_has_no_error(self) -> None:
+ # Get Module ID's DONE; a Move's ACCEPTED and DONE; the host-alive NOTICE (sequence 0).
+ for message in ("000000010002" + "008000", "110300AC5001" + "00", "110300AC5002" + "00",
+ "0000000040FE" + "00"): # fmt: skip
+ self.assertIsNone(p.Reply.parse(bytes.fromhex(message)).error_code, message)
+
+ def test_errors_raise_their_kind(self) -> None:
+ cases = {
+ "1103000712" + "0030": NotConfiguredError,
+ "1103000751" + "0031": NotEnabledError,
+ "1103000740" + "0032": NotHomedError,
+ "1003000750" + "000F": InterlockTrippedError,
+ "1003000750" + "0238": MotionError,
+ "110300075002" + "3C0001": MotionError,
+ "1103000750" + "0077": AceError,
+ }
+ for message, kind in cases.items():
+ with self.subTest(message=message):
+ reply = p.Reply.parse(bytes.fromhex(message.replace(" ", "")))
+ with self.assertRaises(kind):
+ reply.raise_for_error("request")
+
+ def test_device_error_follows_the_ace_error(self) -> None:
+ # A Move whose axis left its error window: DONE, ACE error 0x3C, device error 0x0100.
+ reply = p.Reply.parse(bytes.fromhex("110300075002" + "3C0001"))
+ self.assertEqual((reply.error_code, reply.device_error), (0x3C, 0x0100))
+ with self.assertRaisesRegex(MotionError, r"device error 0x100: motion error window exceeded"):
+ reply.raise_for_error("Move Z")
+
+
+class SagianCanTests(unittest.TestCase):
+ """Forwarded SAGIAN CAN messages, worded as the Master Controller's log words them."""
+
+ # Every distinct pattern in the Master Controller's logs (2026-07-27 .. 10-27), with its words.
+ LOGGED = {
+ "00010500000101f7280fbb40": "TO_NODE 05:00 READ SUCCESS F7 28 0F BB 40",
+ "00010500000001f0": "TO_NODE 05:00 ACTION SUCCESS F0",
+ "0001050000020101": "TO_NODE 05:00 WRITE SUCCESS 01",
+ "000105000003016801": "TO_NODE 05:00 EVENT SUCCESS 68 01",
+ "00012300040300": "TO_NODE 23:04 EVENT REQUEST",
+ "00012a00080300": "TO_NODE 2A:08 EVENT REQUEST",
+ }
+
+ def test_logged_messages_read_as_the_master_controller_reads_them(self) -> None:
+ for data, words in self.LOGGED.items():
+ with self.subTest(data=data):
+ self.assertEqual(p.describe_sagian_can(bytes.fromhex(data)), (words, True))
+
+ def test_any_other_status_is_not_called_normal(self) -> None:
+ text, normal = p.describe_sagian_can(bytes.fromhex("00010500000102"))
+ self.assertFalse(normal)
+ self.assertIn("status 0x02", text)
+ self.assertFalse(p.describe_sagian_can(bytes([0, 1]))[1])
+
+
+class RoutineUnsolicitedTests(unittest.TestCase):
+ """Unsolicited messages every session sees, as the instrument sent them (2026-11-09)."""
+
+ @staticmethod
+ def reply(message: str) -> p.Reply:
+ return p.Reply.parse(bytes.fromhex(message))
+
+ def test_a_drive_clearing_its_fault_is_routine(self) -> None:
+ text = p.describe_routine_unsolicited(self.reply("00000000 31ff 007e0000000000000000"))
+ self.assertEqual(text, "drive node 0x7E: fault cleared (EMCY 0000)")
+
+ def test_a_drive_reporting_the_interlock_is_routine(self) -> None:
+ for source in ("01", "02"):
+ with self.subTest(source=source):
+ text = p.describe_routine_unsolicited(
+ self.reply(f"0000000031ff007700100116 04{source}0000")
+ )
+ self.assertEqual(text, "drive node 0x77: interlock active (EMCY 1000)")
+
+ def test_a_move_the_interlock_ended_is_routine(self) -> None:
+ text = p.describe_routine_unsolicited(self.reply("11120000 50fe 0f1604"))
+ self.assertEqual(text, "device 0x11 index 18: move ended, interlock tripped")
+
+ def test_other_messages_are_shown(self) -> None:
+ for message in (
+ "00000000 31ff 007e0010010704010000", # another drive error: interlock tripped (0407)
+ "11120000 50fe 3c0001", # a move ended by its error window
+ "01010000 1003 00ff", # the chassis: the interlock tripped
+ "21010000 1003 0001", # a digital input changed (the door)
+ "00000000 31ff 007e", # too short to read
+ ):
+ with self.subTest(message=message):
+ self.assertIsNone(p.describe_routine_unsolicited(self.reply(message.replace(" ", ""))))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py
new file mode 100644
index 00000000000..009985ef604
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py
@@ -0,0 +1 @@
+"""The Master Controller's multi-step host commands, as recipes the pods run: `homing.py` (`HM`)."""
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py
new file mode 100644
index 00000000000..e3abbdfd119
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py
@@ -0,0 +1,340 @@
+"""Home All, as the Master Controller does it: a recipe of steps per arm type.
+
+Each recipe was read off four Home All runs on one instrument (two after a power cycle, two with the
+instrument already homed, one of those with the Span-8 Z channels not homed) and reproduces every
+request each arm's board was sent, in order. Every target was the same in all four runs whatever
+the axes' positions before homing. Where a Home All leaves X, the Multichannel's Y and the gripper
+axes is each axis's home position in the instrument's motor record (`phome`, carried by its declared
+configuration: `FromHome`); the gripper's two turns on the way are that position turned by 190 and
+90 degrees in the instrument's GR scale, and the plunger's approach is its zero (`AtValue`). The Z
+approaches (the Multichannel's -1000, the Span-8 channels' 9647) are this instrument's logged
+counts, constants until another instrument's logs show where they come from.
+
+A step decides between moving and homing the way the Master Controller does, by asking the board.
+It first sets the axis's move parameters; a board refuses that with "not homed" for an axis that has
+not been homed since power-up, and then the step homes it, otherwise it moves. So one recipe serves
+a cold start, a homed instrument, and anything between.
+
+The steps, as the requests they send (E = Set State ENABLED, P = Set Move Parameters at the axis's
+maximum speeds, M = Move, H = Home, S = Stop Motion Service, MA = Move All):
+
+ Home(axis, approach) E P; homed: M [E] H; not homed: [E] H. The Span-8 board's sequence
+ has the bracketed E, the Multichannel board's does not.
+ Retract(axis, target) E P; homed: M; not homed: S E P, then [E] H.
+ MoveTo(axis, target) E P M.
+ RetractGroup(axes, target) E P on every axis together; homed: MA; not homed: S, home the axes
+ in pairs (E E H H), then E P on every axis again, MA.
+ HomeGroup(...) the Span-8's Y and Z channels: E P on Y1-Y8 at 0; homed: MA; not
+ homed: S. Then E on Y1-Y8, H Y1, home the Z channels in pairs, E P the
+ Z channels to their target, MA.
+
+That is the Master Controller's Home All, which homes again an axis already homed: `force=True`.
+Without it, an axis that was homed before the run began is only moved, and ends where a Home
+would have left it: a Home step moves it to its approach and stops there (a Home leaves an axis at
+its approach, to a few counts: the Multichannel's Z read -1000 six times out of six after Biomek's
+homes, its plunger 43175-43178 for 43176, the gripper and Y axes 0 or -1), and a HomeGroup whose
+channels were all homed before skips homing Y1 and the Z pairs. An axis the run itself homed is
+homed again where the recipe says, as Biomek does (the gripper Z is homed twice at a cold start).
+Every other request, and the order of every move, is the same either way; on an instrument with no
+axis homed the two send the same requests.
+"""
+
+import logging
+import math
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Dict, List, Sequence, Set, Tuple, Union
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.errors import NotHomedError
+from pylabrobot.beckman_coulter.biomek_i7.driver.motors import AxisMove
+
+if TYPE_CHECKING:
+ from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class FromHome:
+ """The axis's home position in the pod's motor record (`AxisTable.home_position`), turned by
+ `degrees` in the pod's conversion for the axis: the turn's counts, rounded down, added to it. Both
+ logged turns fit that (190 and 90 degrees from the gripper's home, -71487.4 and -33862.4 counts
+ in this instrument's scale, were sent 71488 and 33863 counts on); another rounding would be at
+ most a count, 0.003 degrees, off."""
+
+ degrees: float = 0.0
+
+
+@dataclass(frozen=True)
+class AtValue:
+ """The counts for `value` in the pod's conversion for the axis (`PodConfiguration.to_counts`)."""
+
+ value: float
+
+
+Target = Union[int, FromHome, AtValue]
+
+
+@dataclass(frozen=True)
+class Home:
+ axis: str
+ approach: Target
+
+
+@dataclass(frozen=True)
+class Retract:
+ axis: str
+ target: int
+
+
+@dataclass(frozen=True)
+class MoveTo:
+ axis: str
+ target: Target
+
+
+@dataclass(frozen=True)
+class RetractGroup:
+ axes: Tuple[str, ...]
+ target: int
+ home_pairs: Tuple[Tuple[str, str], ...]
+
+
+@dataclass(frozen=True)
+class HomeGroup:
+ probe_axes: Tuple[str, ...]
+ probe_target: int
+ enable_axes: Tuple[str, ...]
+ home_axis: str
+ then: RetractGroup
+
+
+Step = Union[Home, Retract, MoveTo, RetractGroup, HomeGroup]
+
+# The Span-8's Z channels, in the orders the Master Controller uses for them.
+_SPAN8_Z = RetractGroup(
+ axes=("Z7", "Z8", "Z5", "Z6", "Z3", "Z4", "Z1", "Z2"),
+ target=9647,
+ home_pairs=(("Z1", "Z5"), ("Z2", "Z6"), ("Z3", "Z7"), ("Z4", "Z8")),
+)
+
+# The Master Controller's `HM`: every axis but the plunger.
+HOME_RECIPES: Dict[str, Tuple[Step, ...]] = {
+ "multichannel": (
+ Home("Z", -1000),
+ Retract("GZ", 0),
+ Home("GG", 0),
+ MoveTo("GG", FromHome()),
+ Home("GR", 0),
+ MoveTo("GR", FromHome(190.0)),
+ MoveTo("GR", FromHome(90.0)),
+ Home("GY", 0),
+ Home("GZ", 0),
+ MoveTo("GY", FromHome()),
+ Home("Y", 0),
+ MoveTo("Y", FromHome()),
+ MoveTo("GR", FromHome()),
+ Home("X", 0),
+ MoveTo("X", FromHome()),
+ ),
+ "span8": (
+ _SPAN8_Z,
+ Retract("GZ", 0),
+ Home("GG", 0),
+ MoveTo("GG", FromHome()),
+ Home("GR", 0),
+ MoveTo("GR", FromHome(190.0)),
+ MoveTo("GR", FromHome(90.0)),
+ Home("GY", 0),
+ Home("GZ", 0),
+ MoveTo("GY", FromHome()),
+ HomeGroup(
+ probe_axes=("Y7", "Y8", "Y5", "Y6", "Y3", "Y4", "Y1", "Y2"),
+ probe_target=0,
+ enable_axes=("Y2", "Y4", "Y3", "Y6", "Y5", "Y8", "Y7", "Y1"),
+ home_axis="Y1",
+ then=_SPAN8_Z,
+ ),
+ MoveTo("GR", FromHome()),
+ Home("X", 0),
+ MoveTo("X", FromHome()),
+ ),
+}
+
+# Whether the board's sequence enables an axis again right before homing it.
+ENABLE_BEFORE_HOME = {"multichannel": False, "span8": True}
+
+# The order the Master Controller enables every axis in after the interlock is armed, and reads
+# their positions in. The Multichannel board is sent one Z enable first.
+ENABLE_ORDER: Dict[str, Tuple[str, ...]] = {
+ "multichannel": ("GZ", "GR", "GY", "GG", "Z", "D", "X", "Y"),
+ "span8": (
+ "GR", "GG", "GZ", "D8", "GY", "D6", "D7", "D4", "D5", "D2", "D3", "Z8", "D1", "Z6", "Z7",
+ "Z4", "Z5", "Z2", "Z3", "Y8", "Z1", "Y6", "Y7", "Y4", "Y5", "Y2", "Y3", "X", "Y1",
+ ),
+} # fmt: skip
+ENABLE_PREFIX: Dict[str, Tuple[str, ...]] = {"multichannel": ("Z",), "span8": ()}
+
+
+class Homer:
+ """Runs recipes on one pod, through the pod's drive commands (`Pod._unchecked_fw_*`) only.
+
+ Args:
+ pod: the pod whose board is sent the requests.
+ force: home again axes that were homed before the run, as the Master Controller does.
+ """
+
+ def __init__(self, pod: "Pod", force: bool = False):
+ self.pod = pod
+ self.force = force
+ self.enable_before_home = ENABLE_BEFORE_HOME[pod.module_type]
+ self._homed_in_run: Set[str] = set()
+
+ def _keep_home(self, axes: Sequence[str]) -> bool:
+ """Whether axes that answer homed may be left as they are: not forced, and none of them homed
+ by this run (the recipe's later homes of those are Biomek's own)."""
+ return not self.force and not self._homed_in_run.intersection(axes)
+
+ @staticmethod
+ def _step_targets(step: Step) -> List[Tuple[str, Target]]:
+ if isinstance(step, (Home,)):
+ return [(step.axis, step.approach)]
+ if isinstance(step, (Retract, MoveTo)):
+ return [(step.axis, step.target)]
+ if isinstance(step, RetractGroup):
+ return [(axis, step.target) for axis in step.axes]
+ return [(axis, step.probe_target) for axis in step.probe_axes] + Homer._step_targets(step.then)
+
+ def targets(self, step: Step) -> List[Tuple[str, int]]:
+ """Every (axis, position) a step may set move parameters to on this pod, in order."""
+ return [(axis, self._counts(axis, target)) for axis, target in self._step_targets(step)]
+
+ @staticmethod
+ def axes(steps: Sequence[Step]) -> List[str]:
+ """Every axis a recipe moves or homes, once each."""
+ names = [axis for step in steps for axis, _ in Homer._step_targets(step)]
+ return list(dict.fromkeys(names))
+
+ def _counts(self, axis: str, target: Target) -> int:
+ """`target` on this pod's `axis`, in counts.
+
+ Raises:
+ ValueError: for a turn or a value on a pod with no declared configuration to convert it.
+ """
+ if isinstance(target, int):
+ return target
+ if isinstance(target, FromHome) and not target.degrees:
+ return self.pod.axis(axis).home_position
+ declared = self.pod.declared
+ if declared is None:
+ raise ValueError(f"{self.pod}: {target} on {axis} needs the pod's declared configuration")
+ if isinstance(target, AtValue):
+ return declared.to_counts(axis, target.value)
+ turn = target.degrees * declared.conversion[axis].const
+ return self.pod.axis(axis).home_position + math.floor(turn)
+
+ async def run(self, steps: Sequence[Step]) -> None:
+ for step in steps:
+ logger.debug("%s: %s", self.pod, step)
+ if isinstance(step, Home):
+ await self._home(step)
+ elif isinstance(step, Retract):
+ await self._retract(step)
+ elif isinstance(step, MoveTo):
+ await self._move_to(step)
+ elif isinstance(step, RetractGroup):
+ await self._retract_group(step)
+ else:
+ await self._home_group(step)
+
+ # -- drive commands --------------------------------------------------------
+
+ async def _enable(self, names: Sequence[str]) -> None:
+ await self.pod._unchecked_fw_enable(names)
+
+ async def _probe(self, names: Sequence[str], target: int) -> bool:
+ """Set move parameters on every axis at its maximum speeds; True if the board took them all,
+ False if any axis is not homed."""
+ accepted = await self.pod._unchecked_fw_set_move_parameters(
+ [AxisMove(name, target) for name in names]
+ )
+ if not all(accepted) and any(accepted):
+ # Only all-or-none was seen; homing every axis of the group is the safe reading.
+ logger.warning("%s: some of %s are homed and some are not; homing them all", self.pod, names)
+ return all(accepted)
+
+ async def _stop(self) -> None:
+ await self.pod._unchecked_fw_stop_motion()
+
+ async def _move(self, name: str) -> None:
+ await self.pod._unchecked_fw_move(name)
+
+ async def _move_all(self) -> None:
+ await self.pod._unchecked_fw_move_all()
+
+ async def _home_axes(self, names: Sequence[str]) -> None:
+ await self.pod._unchecked_fw_home(names)
+ self._homed_in_run.update(names)
+
+ # -- steps -----------------------------------------------------------------
+
+ async def _home(self, step: Home) -> None:
+ await self._enable([step.axis])
+ if await self._probe([step.axis], self._counts(step.axis, step.approach)):
+ await self._move(step.axis)
+ if self._keep_home([step.axis]):
+ return
+ if self.enable_before_home:
+ await self._enable([step.axis])
+ await self._home_axes([step.axis])
+
+ async def _retract(self, step: Retract) -> None:
+ await self._enable([step.axis])
+ if await self._probe([step.axis], step.target):
+ await self._move(step.axis)
+ return
+ await self._stop()
+ await self._enable([step.axis])
+ if await self._probe([step.axis], step.target):
+ await self._move(step.axis)
+ return
+ if self.enable_before_home:
+ await self._enable([step.axis])
+ await self._home_axes([step.axis])
+
+ async def _move_to(self, step: MoveTo) -> None:
+ await self._enable([step.axis])
+ if not await self._probe([step.axis], self._counts(step.axis, step.target)):
+ raise NotHomedError(0x32, None, f"{self.pod}: {step.axis} is not homed for {step}")
+ await self._move(step.axis)
+
+ async def _home_pairs(self, pairs: Sequence[Tuple[str, str]]) -> None:
+ for pair in pairs:
+ await self._enable(pair)
+ await self._home_axes(pair)
+
+ async def _retract_group(self, step: RetractGroup) -> None:
+ await self._enable(step.axes)
+ if not await self._probe(step.axes, step.target):
+ await self._stop()
+ await self._home_pairs(step.home_pairs)
+ await self._enable(step.axes)
+ if not await self._probe(step.axes, step.target):
+ raise NotHomedError(0x32, None, f"{self.pod}: {step.axes} still not homed after homing")
+ await self._move_all()
+
+ async def _home_group(self, step: HomeGroup) -> None:
+ await self._enable(step.probe_axes)
+ homed = await self._probe(step.probe_axes, step.probe_target)
+ if homed:
+ await self._move_all()
+ else:
+ await self._stop()
+ group = (step.home_axis, *step.probe_axes, *step.then.axes)
+ if not homed or not self._keep_home(group):
+ await self._enable(step.enable_axes)
+ await self._home_axes([step.home_axis])
+ await self._home_pairs(step.then.home_pairs)
+ await self._enable(step.then.axes)
+ if not await self._probe(step.then.axes, step.then.target):
+ raise NotHomedError(0x32, None, f"{self.pod}: {step.then.axes} still not homed after homing")
+ await self._move_all()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py
new file mode 100644
index 00000000000..f77e3888fc4
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py
@@ -0,0 +1,142 @@
+"""The checks that tie a declared configuration to one instrument, on the instrument's own path:
+its serial numbers, and its Biomek files still matching. The replayed generic cold start answers placeholder serial numbers, as long
+as real ones; a configuration copy naming them stands for that instrument's own.
+
+The instrument's path (no `boards` given) is taken with the replayed boards attached where `_open`
+would open the USB devices, so `discover` runs exactly as on the instrument."""
+
+import asyncio
+import dataclasses
+import tempfile
+import unittest
+from pathlib import Path
+from typing import Iterator, List
+from unittest import mock
+
+from pylabrobot.beckman_coulter.biomek_i7.biomek_files.files_tests_support import (
+ write_instrument_file,
+ write_record,
+)
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration
+from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver
+from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import (
+ GENERIC_SERIAL_NUMBERS,
+ as_instrument,
+ configuration_file,
+ generic_boards,
+ generic_configuration,
+ generic_driver,
+ sealed,
+)
+
+MASTER_LOGGER = "pylabrobot.beckman_coulter.biomek_i7.driver.master"
+READS = {name for name in p.COMMANDS.values() if name.startswith(("Get ", "Read ", "List "))}
+
+
+class InstrumentPathTests(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self) -> None:
+ asyncio.get_running_loop().set_debug(False)
+ self.boards: List[AceBoard] = []
+
+ def driver(self, configuration: DeviceConfiguration) -> BiomekI7Driver:
+ driver = BiomekI7Driver(declared_configuration_json=configuration_file(configuration))
+ self.boards = boards = generic_boards()
+
+ async def attach() -> None:
+ driver.boards = list(boards)
+ driver._connected = True
+ for board in driver.boards:
+ await board.setup()
+
+ patcher = mock.patch.object(driver, "_open", attach)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.addAsyncCleanup(driver.stop)
+ return driver
+
+ def requests(self) -> Iterator[str]:
+ for board in self.boards:
+ assert isinstance(board.io, ReplayAceUSB)
+ for message in board.io.requests:
+ yield p.COMMANDS[(message[0], message[4])]
+
+ async def test_the_instruments_own_configuration_is_accepted(self) -> None:
+ driver = self.driver(as_instrument(generic_configuration()))
+ await driver.discover()
+ self.assertEqual(await driver.request_serial_numbers(), GENERIC_SERIAL_NUMBERS)
+ self.assertEqual(set(self.requests()) - READS, set())
+
+ async def test_another_instruments_serial_number_is_refused_before_anything_is_written(
+ self,
+ ) -> None:
+ config = as_instrument(generic_configuration())
+ config.pods["right"] = dataclasses.replace(config.pods["right"], module_serial_number="X" * 32)
+ driver = self.driver(sealed(config))
+ with self.assertRaisesRegex(ValueError, "right pod module X{32}, found SIMULATED009"):
+ await driver.setup()
+ self.assertEqual(set(self.requests()) - READS, set())
+
+ async def test_another_chassis_is_refused(self) -> None:
+ config = as_instrument(generic_configuration())
+ config.chassis_serial_number = "Y" * 32
+ with self.assertRaisesRegex(ValueError, "chassis Y{32}, found SIMULATED001"):
+ await self.driver(sealed(config)).discover()
+
+ async def test_the_generic_configuration_is_refused_even_with_matching_numbers(self) -> None:
+ config = as_instrument(generic_configuration())
+ config.generic = True
+ with self.assertRaisesRegex(ValueError, "generic"):
+ await self.driver(sealed(config)).discover()
+
+ async def test_the_generic_configuration_is_refused(self) -> None:
+ with self.assertRaisesRegex(ValueError, "generic configuration.*chassis not recorded"):
+ await self.driver(generic_configuration()).discover()
+
+
+class SourcesTests(InstrumentPathTests):
+ """A configuration imported from Biomek files written in the test, as the instrument's own."""
+
+ async def asyncSetUp(self) -> None:
+ await super().asyncSetUp()
+ folder = tempfile.TemporaryDirectory()
+ self.addCleanup(folder.cleanup)
+ self.bif, self.record = Path(folder.name) / "Biomek_i7.bif", Path(folder.name) / "record.txt"
+ self.instrument = as_instrument(generic_configuration())
+ write_instrument_file(self.instrument, self.bif)
+ write_record(self.instrument, self.record)
+ self.imported = DeviceConfiguration.from_biomek(self.bif, master_controller_record=self.record)
+
+ async def test_matching_sources_are_accepted(self) -> None:
+ with self.assertNoLogs(MASTER_LOGGER, "WARNING"):
+ await self.driver(self.imported).discover()
+
+ async def test_a_re_measured_hysteresis_makes_it_stale(self) -> None:
+ next(a for a in self.instrument.modules["span8"] if a["name"] == "Z3")["hysteresis"] = 4
+ write_record(self.instrument, self.record)
+ with self.assertRaisesRegex(ValueError, r"no longer matches.*hysteresis: 0 -> 4.*from_biomek"):
+ await self.driver(self.imported).discover()
+ self.assertEqual(set(self.requests()) - READS, set())
+
+ async def test_sources_not_found_here_are_warned_about(self) -> None:
+ self.bif.unlink()
+ with self.assertLogs(MASTER_LOGGER, "WARNING") as logs:
+ await self.driver(self.imported).discover()
+ self.assertIn("cannot be read here", " ".join(logs.output))
+
+
+class SimulationTests(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self) -> None:
+ asyncio.get_running_loop().set_debug(False)
+
+ async def test_a_simulation_is_not_tied_to_an_instrument(self) -> None:
+ driver = generic_driver() # the generic configuration, no serial numbers
+ self.addAsyncCleanup(driver.stop)
+ await driver.discover()
+ self.assertTrue(driver.declared.generic)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py
new file mode 100644
index 00000000000..9f0011ca412
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py
@@ -0,0 +1,480 @@
+"""Simulated instruments: boards that answer from what a real Biomek i7's boards answered.
+
+`ReplayAceUSB` only replays a recording. `SimulatedAceUSB` also models each axis (homed or not,
+its position, its pending move), so configuring, arming and homing can run against it; nothing it
+does reaches a USB device.
+
+A replayed board holds a recording of request -> replies, keyed on everything in a request
+but its sequence number, and answers a request it has a recording for with those replies under
+the request's sequence number. A request it has no recording for gets no answer, as a board that
+ignored it would, and is kept in `unanswered`.
+"""
+
+import asyncio
+import gzip
+import json
+import math
+import os
+import struct
+from dataclasses import dataclass
+from pathlib import Path
+from typing import (
+ Any,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Sequence,
+ Tuple,
+ Union,
+)
+
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard
+from pylabrobot.beckman_coulter.biomek_i7.driver.framing import frame, split
+from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, MotorTables
+from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import (
+ LLS_LIQUID_SENSED,
+ AxisState,
+ Device,
+)
+from pylabrobot.io.usb import USB
+
+# Names the recording the simulator answers from (identity and sensor reads, recorded at an
+# instrument's cold start) when no path is given. A generic one ships in `defaults/`
+# (`biomek_i7_generic_coldstart.json`).
+RECORDING_ENV = "BIOMEK_I7_SIMULATOR_RECORDING"
+
+
+def recording_path(path: Optional[Union[str, Path]] = None) -> Path:
+ """`path`, else the file `$BIOMEK_I7_SIMULATOR_RECORDING` names.
+
+ Raises:
+ ValueError: with neither.
+ """
+ path = path or os.environ.get(RECORDING_ENV)
+ if not path:
+ raise ValueError(
+ f"no recording for the simulator to answer from: pass its path or set ${RECORDING_ENV}"
+ )
+ return Path(path)
+
+
+def load_recording(path: Optional[Union[str, Path]] = None) -> Dict[str, Any]:
+ """A recording (`recording_path`), gzipped (`.gz`) or not."""
+ where = recording_path(path)
+ if where.suffix == ".gz":
+ with gzip.open(where, "rt", encoding="utf-8") as fh:
+ return dict(json.load(fh))
+ with open(where, encoding="utf-8") as fh:
+ return dict(json.load(fh))
+
+
+def _request_key(message: bytes) -> str:
+ return (message[:3] + message[4:]).hex()
+
+
+class ReplayAceUSB(USB):
+ """One board's USB link, answered from a recording."""
+
+ def __init__(self, recording: Dict[str, List[str]], name: str = "replayed ACE board"):
+ super().__init__(0x0AB5, 0xACE0, name)
+ self.recording = {k: [bytes.fromhex(r) for r in v] for k, v in recording.items()}
+ self.requests: List[bytes] = []
+ self.unanswered: List[bytes] = []
+ self._packets: "asyncio.Queue[bytes]" = asyncio.Queue()
+
+ async def setup(self, empty_buffer=True):
+ pass
+
+ async def stop(self):
+ pass
+
+ async def write(self, data: bytes, timeout: Optional[float] = None):
+ for message in split(data):
+ self.requests.append(message)
+ replies = self.recording.get(_request_key(message))
+ if replies is None:
+ self.unanswered.append(message)
+ continue
+ for reply in replies:
+ framed = frame(reply[:3] + message[3:4] + reply[4:])
+ for i in range(0, len(framed), 16):
+ self._packets.put_nowait(framed[i : i + 16])
+
+ async def read(self, timeout=None, size=None, endpoint=None) -> bytes:
+ try:
+ return await asyncio.wait_for(self._packets.get(), timeout=0.05)
+ except asyncio.TimeoutError:
+ raise TimeoutError("no packet") from None
+
+
+def replay_boards(
+ path: Optional[Union[str, Path]] = None, default_timeout: float = 1.0
+) -> List[AceBoard]:
+ """One replayed board per module in a recording (`recording_path`), as
+ `BiomekI7Driver(boards=...)` takes them."""
+ data = load_recording(path)
+ return [
+ AceBoard(
+ io=ReplayAceUSB(dict(entries), name=f"replayed {module}"),
+ name=f"replayed {module}",
+ default_timeout=default_timeout,
+ )
+ for module, entries in data["boards"].items()
+ ]
+
+
+# Axes a Home of one axis also homes. Biomek homes only Y1 of the Span-8's eight Y channels, and
+# after its Home All every one of them reads as homed (H1, 2026-10-24).
+LINKED_HOMES: Dict[str, Dict[str, Tuple[str, ...]]] = {
+ "span8": {
+ "Y1": tuple(f"Y{i}" for i in range(1, 9)),
+ "D1": tuple(f"D{i}" for i in range(1, 9)), # the pumps (`HD`, 2026-10-09)
+ },
+}
+
+
+class SimulatedAceUSB(ReplayAceUSB):
+ """One board's USB link, answered from a model of its axes rather than only a recording.
+
+ Each axis has a state (`AxisState`), is homed or not, and has a position and a pending move, by
+ the boards' rules: an axis starts not configured; Configure leaves it
+ disabled and not homed; Set State and Set Move Parameters are refused "not configured" before
+ that; Home is refused "not enabled" unless the axis is enabled. Set Move Parameters is refused
+ "not homed" for an axis not homed, as a board refuses it after power-up; Move, Move All and Home
+ answer ACCEPTED then DONE and update the model. A homed axis ends at 0 in the model; a real
+ board ends where its Configure parameters say (Biomek read the Multichannel's Z at -1000 and its
+ plunger at 43175 straight after homing). Identity and sensor reads are answered from the
+ recording.
+
+ The boards of one instrument share an `Interlock`. While it is tripped, as at rest, a CiA 402
+ axis that was enabled reads FAULT (its drive lost motor power: H1, 2026-10-27; one configured at
+ rest reads DISABLED, as on H2 the same day), its enable fails, moves and homes
+ are refused "interlock tripped", and the arm's drive supply input reads 0.12 V; armed, 35.4 V.
+ Enabling a CiA 402 axis in fault resets it, unless it was given a fault that
+ does not clear (`_AxisModel.stuck_fault`). The error codes of a failed enable are not known; the
+ model answers "interlock tripped" without power and 0x3D for a stuck fault.
+
+ A move with a force limit stops where the axis meets something (`_AxisModel.obstacle`, set by a
+ test). A move with a sensor stops where the sensor fires (`_AxisModel.sensed_at`), and the
+ Move All carries that axis's report (LLS_LIQUID_SENSED and the position) under its sequence.
+ A pump keeps the valve it was last moved through.
+
+ Moves complete at once unless `time_scale` is set: then a Move or Move All is accepted at once
+ and done after the slowest axis's move would take (`_AxisModel.duration`), times `time_scale`
+ (1: about as long as on the instrument), so a simulated run can be watched and stopped.
+ """
+
+ def __init__(
+ self,
+ recording: Dict[str, List[str]],
+ axes: Sequence[Axis] = (),
+ homed: Iterable[str] = (),
+ name: str = "simulated ACE board",
+ linked_homes: Optional[Dict[str, Tuple[str, ...]]] = None,
+ configured: bool = False,
+ interlock: Optional["Interlock"] = None,
+ supply_input: Optional[int] = None,
+ door_input: Optional[int] = None,
+ time_scale: float = 0.0,
+ ):
+ super().__init__(recording, name=name)
+ self.time_scale = time_scale
+ self._move_seconds = 0.0 # how long the move just answered takes (`answer`)
+ self.door_input = door_input
+ homed = set(homed)
+ if homed and not configured:
+ raise ValueError("an axis cannot be homed on a board that is not configured")
+ self.linked_homes = linked_homes or {}
+ self.interlock = interlock or Interlock()
+ self.supply_input = supply_input
+ self.axes: Dict[Tuple[int, int], _AxisModel] = {}
+ for a in axes:
+ # At rest a configured instrument's SAGIAN axes read ENABLED, as on 2026-10-27; CiA 402
+ # axes read FAULT while the interlock is tripped (`_apply_power`).
+ state = AxisState.ENABLED if configured else AxisState.NOT_CONFIGURED
+ self.axes[(a.device, a.index)] = _AxisModel(a.name, a.name in homed, state, a.drive)
+ self.axes_list = list(axes)
+
+ def _apply_power(self) -> None:
+ """An enabled CiA 402 drive faults when its motor power goes. One configured with the power
+ already off stays DISABLED (H2, 2026-10-27: every axis read DISABLED after the Master
+ Controller's Configure at rest)."""
+ if self.interlock.armed:
+ return
+ for model in self.axes.values():
+ if model.drive == "cia402" and model.state == AxisState.ENABLED:
+ model.state = AxisState.FAULT
+
+ def set_door(self, open_: bool) -> None:
+ """Open or close the door, on the chassis's link: the door sensor reports the change; the
+ interlock is not affected (as in Biomek's logs)."""
+ self.interlock.door_open = open_
+ self._queue(
+ bytes([Device.DIGITAL_INPUT, self.door_input or 1, 0, 0, 0x10, 0x03, 0, int(not open_)])
+ )
+
+ def set_light_curtain(self, broken: bool) -> None:
+ """Break or clear the light curtain: breaking it trips an armed interlock, which reports it
+ (Notify On Interlock Trip); while broken, the interlock does not arm."""
+ self.interlock.light_curtain_broken = broken
+ if broken and self.interlock.armed:
+ self.interlock.armed = False
+ self._queue(bytes([Device.INTERLOCK, 1, 0, 0, 0x10, 0x03, 0, 0xFF]))
+
+ def axis_model(self, name: str) -> "_AxisModel":
+ for model in self.axes.values():
+ if model.name == name:
+ return model
+ raise KeyError(name)
+
+ def answer(self, message: bytes) -> Optional[List[bytes]]:
+ device, index, opcode, params = message[0], message[1], message[4], message[5:]
+ header = message[:5]
+ done = header + b"\x02\x00"
+ accepted = header + b"\x01\x00"
+ tripped = header + b"\x00\x0f"
+ self._apply_power()
+ if device == Device.ANALOG_INPUT and opcode == 0x10 and index == self.supply_input:
+ powered = self.interlock.armed and self.interlock.supply_comes_up
+ return [done + struct.pack(" 0 and len(replies) > 1:
+ # Accepted now; the rest (reports, done) once the move would have finished.
+ self._queue(replies[0])
+ asyncio.get_running_loop().call_later(delay, self._queue_all, replies[1:])
+ continue
+ self._queue_all(replies)
+
+ def _queue_all(self, replies: List[bytes]) -> None:
+ for reply in replies:
+ self._queue(reply)
+
+ def _queue(self, message: bytes) -> None:
+ framed = frame(message)
+ for i in range(0, len(framed), 16):
+ self._packets.put_nowait(framed[i : i + 16])
+
+
+@dataclass
+class Interlock:
+ """The interlock one instrument's simulated boards share. `supply_comes_up=False` models an
+ interlock that arms while the drive supply stays off."""
+
+ armed: bool = False
+ supply_comes_up: bool = True
+ door_open: bool = False
+ light_curtain_broken: bool = False
+
+
+@dataclass
+class _AxisModel:
+ name: str
+ homed: bool
+ state: AxisState = AxisState.NOT_CONFIGURED
+ drive: str = "cia402"
+ stuck_fault: bool = False
+ position: int = 0
+ pending: Optional[int] = None
+ # The pending move's force limit (x1000) and sensor; a pump's valve (0-3, None until moved).
+ force: int = 0
+ sensor: int = 0
+ valve: Optional[int] = None
+ # Where a force-limited move meets something, and where a sensor fires; None: nowhere.
+ obstacle: Optional[int] = None
+ sensed_at: Optional[int] = None
+ # The pending move's top speed (counts/s) and acceleration (counts/s2), as last set.
+ velocity: int = 0
+ acceleration: int = 0
+
+ def duration(self) -> float:
+ """Seconds the pending move takes: up to speed, at speed, down again (jerk left out); 0
+ with none, or without speeds."""
+ if self.pending is None or self.velocity <= 0 or self.acceleration <= 0:
+ return 0.0
+ distance = abs(self.pending - self.position)
+ v, a = float(self.velocity), float(self.acceleration)
+ if distance >= v * v / a:
+ return distance / v + v / a
+ return 2.0 * math.sqrt(distance / a)
+
+ def finish_move(self) -> Optional[str]:
+ """Run the pending move to its end: its target, or where force or a sensor stops it. Returns
+ "stalled" or "sensed" for those, else None."""
+ if self.pending is None:
+ return None
+ low, high = sorted((self.position, self.pending))
+ target, self.pending = self.pending, None
+ obstacle, sensed_at = self.obstacle, self.sensed_at
+ # An obstacle stops a force-limited move into it, not one leaving it.
+ if (
+ self.force and obstacle is not None and obstacle != self.position and low <= obstacle <= high
+ ):
+ self.position = obstacle
+ return "stalled"
+ if self.sensor and sensed_at is not None and low <= sensed_at <= high:
+ self.position = sensed_at
+ return "sensed"
+ self.position = target
+ return None
+
+
+# The analog input carrying the interlocked drive supply, per module (the Master Controller's cold
+# start: "+36V Interlocked" is the chassis's input 5, "+36V Interlock" each arm's input 4).
+SUPPLY_INPUTS = {"chassis": 5, "multichannel": 4, "span8": 4}
+# The chassis's digital input 1 is "Door Sensor".
+DOOR_INPUTS = {"chassis": 1}
+
+
+def simulated_boards(
+ motor_tables: MotorTables,
+ homed: Union[bool, Dict[str, Iterable[str]]] = False,
+ path: Optional[Union[str, Path]] = None,
+ default_timeout: float = 1.0,
+ configured: Optional[Union[bool, Dict[str, bool]]] = None,
+ time_scale: float = 0.0,
+) -> List[AceBoard]:
+ """A simulated instrument as `BiomekI7Driver(boards=...)` takes it: the recorded chassis, a left
+ Multichannel and a right Span-8 pod.
+
+ Args:
+ motor_tables: the axes to model: the declared configuration's
+ (`DeviceConfiguration.motor_tables`), the one the driver is given.
+ homed: True for every axis homed, False for none, or the homed axes' names per arm type.
+ path: the recording that answers identity and sensor reads (`recording_path`).
+ configured: whether each arm's board has its motor tables, as one value or per arm type.
+ Defaults to configured wherever an axis is homed, and not configured (just powered up)
+ otherwise.
+ time_scale: how long moves take, as `SimulatedAceUSB` takes it (0: at once).
+ """
+ tables = motor_tables
+ data = load_recording(path)
+ interlock = Interlock()
+ boards = []
+ for module, entries in data["boards"].items():
+ axes = tables.axes(module) if module in tables.modules else []
+ if isinstance(homed, bool):
+ homed_axes: Iterable[str] = [a.name for a in axes] if homed else []
+ else:
+ homed_axes = homed.get(module, [])
+ homed_axes = list(homed_axes)
+ if configured is None:
+ is_configured = bool(homed_axes)
+ elif isinstance(configured, bool):
+ is_configured = configured
+ else:
+ is_configured = configured.get(module, False)
+ usb = SimulatedAceUSB(
+ dict(entries),
+ axes,
+ homed_axes,
+ name=f"simulated {module}",
+ linked_homes=LINKED_HOMES.get(module),
+ configured=is_configured,
+ interlock=interlock,
+ supply_input=SUPPLY_INPUTS.get(module),
+ door_input=DOOR_INPUTS.get(module),
+ time_scale=time_scale,
+ )
+ boards.append(AceBoard(io=usb, name=f"simulated {module}", default_timeout=default_timeout))
+ return boards
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator_tests.py
new file mode 100644
index 00000000000..d8fcebca10c
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator_tests.py
@@ -0,0 +1,80 @@
+"""Replayed boards: what they answer, and what they do not."""
+
+import gzip
+import json
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard
+from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import (
+ RECORDING_ENV,
+ ReplayAceUSB,
+ load_recording,
+ recording_path,
+ replay_boards,
+)
+
+# Get Module ID answered once, and a Move answered twice (ACCEPTED, then DONE); keys leave out the
+# sequence number, and the replies' sequence bytes are placeholders.
+RECORDING = {
+ "00000000": ["000000000002008000"],
+ "1103005030750000": ["11030000500100", "11030000500200"],
+}
+
+
+class ReplayTests(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self) -> None:
+ self.io = ReplayAceUSB(RECORDING)
+ self.board = AceBoard(io=self.io, default_timeout=0.3)
+ await self.board.setup()
+
+ async def asyncTearDown(self) -> None:
+ await self.board.stop()
+
+ async def test_a_recorded_request_is_answered_under_its_own_sequence(self) -> None:
+ for _ in range(3): # each send takes the next sequence number; the recording ignores it
+ reply = await self.board.send(p.get_module_id())
+ self.assertEqual(p.parse_module_id(reply.payload).type, "chassis")
+ self.assertEqual([m[3] for m in self.io.requests], [1, 2, 3])
+ self.assertEqual(self.io.unanswered, [])
+
+ async def test_replies_come_in_their_recorded_order(self) -> None:
+ reply = await self.board.send(p.move(3, 30000))
+ self.assertEqual(reply.status, p.Status.DONE)
+
+ async def test_an_unrecorded_request_gets_no_answer(self) -> None:
+ with self.assertRaises(TimeoutError):
+ await self.board.send(p.get_module_serial_number())
+ self.assertEqual(self.io.unanswered, [p.get_module_serial_number().encode(1)])
+
+
+class RecordingFileTests(unittest.TestCase):
+ def test_gzipped_and_plain_recordings_load(self) -> None:
+ data = {"boards": {"chassis": [["00000000", ["000000000002008000"]]]}}
+ with tempfile.TemporaryDirectory() as folder:
+ plain = Path(folder) / "recording.json"
+ plain.write_text(json.dumps(data), encoding="utf-8")
+ packed = Path(folder) / "recording.json.gz"
+ with gzip.open(packed, "wt", encoding="utf-8") as fh:
+ json.dump(data, fh)
+ self.assertEqual(load_recording(plain), data)
+ self.assertEqual(load_recording(packed), data)
+ boards = replay_boards(packed)
+ self.assertEqual([b.name for b in boards], ["replayed chassis"])
+
+ def test_a_recording_must_be_named(self) -> None:
+ environment = {k: v for k, v in os.environ.items() if k != RECORDING_ENV}
+ with mock.patch.dict(os.environ, environment, clear=True):
+ with self.assertRaisesRegex(ValueError, RECORDING_ENV):
+ recording_path()
+ with mock.patch.dict(os.environ, {RECORDING_ENV: "from-the-environment.json"}):
+ self.assertEqual(recording_path(), Path("from-the-environment.json"))
+ self.assertEqual(recording_path("given.json"), Path("given.json"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py
new file mode 100644
index 00000000000..87de159982e
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py
@@ -0,0 +1,219 @@
+"""The shared X rail: keeps the two pods from running into each other (design.md I7).
+
+Both pods ride one rail and nothing below the driver stops them colliding: the Master
+Controller plans each pod on its own, and each board knows only its pod. Biomek keeps them
+apart. Before a pod moves, its swept range must clear the other pod's
+range; if it does not, the other pod is moved out of the way first and the mover waits. A pod's
+range counts its bridge, its pipettor and its gripper, turned and opened as it is, with what it
+holds (`driver/pod_geometry.py`).
+
+`XRail` applies the same rule. It differs in three ways:
+- **It refuses** a move into where the other pod stands, or will stand once its move ends,
+ rather than moving the other pod; `make_space` comes later.
+- **It waits** when a move conflicts only with a move of the other pod still running, then
+ checks again: the other pod is passing through, not staying (Biomek runs such moves together).
+- **It reserves** every move in flight, so two moves started together cannot pass through each
+ other.
+
+It works from the declared configuration (`driver/configuration.py`), never from the resource
+tree, so it holds with no deck. Poses are in Biomek's units: deck X in cm, GR in degrees, GG in cm.
+"""
+
+import asyncio
+import contextlib
+import logging
+from dataclasses import dataclass
+from typing import AsyncIterator, Awaitable, Callable, Dict, Optional
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration, Side
+
+logger = logging.getLogger(__name__)
+
+OTHER: Dict[Side, Side] = {"left": "right", "right": "left"}
+
+# How long a move waits for the other pod's move to clear, in seconds. Longer than any single
+# move (the Master Controller's Move All timeouts are seconds), so a wait this long means
+# something is stuck.
+WAIT_TIMEOUT = 120.0
+
+
+class RailCollisionError(ValueError):
+ """A move would bring a pod into the other pod's X range. Raised before anything is sent."""
+
+
+@dataclass(frozen=True)
+class PodPose:
+ """Where a pod is, as the rail needs it: deck X (cm) and its gripper's pose, None when not
+ known (then every pose the gripper could take is counted)."""
+
+ x: float
+ gripper: Optional[g.GripperPose] = None
+
+
+class XRail:
+ """Where each pod is on the rail, and what each pod's move in flight has reserved.
+
+ Args:
+ pods: the declared configuration of each pod on the rail. A side with None has a pod whose
+ geometry is not declared: it cannot be guarded, so neither pod may move.
+ """
+
+ def __init__(self, pods: Dict[Side, Optional[PodConfiguration]]):
+ self.pods = pods
+ self._pose: Dict[Side, Optional[PodPose]] = {side: None for side in pods}
+ self._reserved: Dict[Side, Optional[g.Range]] = {side: None for side in pods}
+ self._end: Dict[Side, Optional[g.Range]] = {side: None for side in pods}
+ self._done: Dict[Side, asyncio.Event] = {side: asyncio.Event() for side in pods}
+ self._lock = asyncio.Lock()
+ # How to read a pod's pose when the rail does not know it. Set by the driver.
+ self.readers: Dict[Side, Callable[[], Awaitable[PodPose]]] = {}
+ self._models = {
+ side: g.GripperModel.from_bif(p.gripper_model) if p and p.gripper_model else None
+ for side, p in pods.items()
+ }
+
+ def _require_pod(self, side: Side) -> PodConfiguration:
+ pod = self.pods.get(side)
+ if pod is None:
+ raise RuntimeError(
+ f"the {side} pod has no declared geometry, so the X rail cannot keep the pods apart; "
+ "pass a declared configuration that includes it"
+ )
+ return pod
+
+ def _gripper(self, side: Side, pose: Optional[g.GripperPose]) -> Optional[g.Gripper]:
+ model = self._models.get(side)
+ if model is None or pose is None:
+ return None
+ return g.Gripper(model, pose)
+
+ def range_at(self, side: Side, pose: PodPose) -> g.Range:
+ """The X a pod takes up at a pose. An unknown gripper pose counts every pose it could take:
+ the whole of GR's travel, fully open."""
+ pod = self._require_pod(side)
+ if pose.gripper is not None or self._models.get(side) is None:
+ return g.pod_x_range(pod.geometry, pose.x, self._gripper(side, pose.gripper))
+ return self.swept(side, PodPose(pose.x, None), PodPose(pose.x, None))
+
+ def swept(self, side: Side, start: PodPose, end: PodPose) -> g.Range:
+ """The X a pod takes up while moving from `start` to `end`."""
+ pod = self._require_pod(side)
+ a, b = start.gripper, end.gripper
+ if self._models.get(side) is not None and (a is None or b is None):
+ # Not known: count every pose the gripper could take, fully open, holding what it holds.
+ known = a or b
+ held = known.held if known is not None else None
+ gr_low, gr_high = pod.limits["GR"]
+ gg_open = pod.limits["GG"][1]
+ a, b = g.GripperPose(gr_low, gg_open, held), g.GripperPose(gr_high, gg_open, held)
+ return g.swept_x_range(
+ pod.geometry, start.x, end.x, self._gripper(side, a), self._gripper(side, b)
+ )
+
+ def update(self, side: Side, pose: Optional[PodPose]) -> None:
+ """Record where a pod is, or None when not known (after homing, or a move that failed). A
+ known pose ends the reservation a failed move left, but never one of a move still running: a
+ read can come back after that move started."""
+ if side not in self.pods:
+ return
+ self._pose[side] = pose
+ if pose is not None and not self._in_flight(side):
+ self._reserved[side] = None
+
+ def _in_flight(self, side: Side) -> bool:
+ return self._end[side] is not None
+
+ def occupied(self, side: Side) -> Optional[g.Range]:
+ """The X a pod takes up now: its move's reservation while one is in flight or a failed one
+ left, else its range where it is. None when its position is not known."""
+ if self._reserved.get(side) is not None:
+ return self._reserved[side]
+ pose = self._pose.get(side)
+ return None if pose is None else self.range_at(side, pose)
+
+ def check(self, side: Side, start: PodPose, end: PodPose) -> g.Range:
+ """Check a move of `side` against the other pod. Returns the move's swept range.
+
+ Raises:
+ RailCollisionError: if the swept range overlaps where the other pod stands, or will stand
+ once its move ends.
+ RuntimeError: if the other pod's position is not known and the move goes towards it, or a
+ pod on the rail has no declared geometry.
+ """
+ swept = self.swept(side, start, end)
+ other = OTHER[side]
+ if other not in self.pods:
+ return swept
+ self._require_pod(other)
+ end_range = self._end.get(other)
+ if end_range is not None: # the other pod is moving
+ if g.grid_overlap(swept, end_range):
+ raise self._collision(side, swept, other, end_range, "will stand")
+ return swept # any overlap with its sweep is waited out in `moving`
+ taken = self.occupied(other)
+ if taken is None:
+ if (
+ (swept[1] > self.range_at(side, start)[1])
+ if side == "left"
+ else (swept[0] < self.range_at(side, start)[0])
+ ):
+ raise RuntimeError(
+ f"the {other} pod's position is not known, and the {side} pod's move goes towards it"
+ )
+ return swept
+ if g.grid_overlap(swept, taken):
+ raise self._collision(side, swept, other, taken, "stands")
+ return swept
+
+ def _collision(
+ self, side: Side, swept: g.Range, other: Side, taken: g.Range, how: str
+ ) -> RailCollisionError:
+ return RailCollisionError(
+ f"the {side} pod's move would take up deck X {swept[0]:.2f}..{swept[1]:.2f} cm, into "
+ f"{taken[0]:.2f}..{taken[1]:.2f}, where the {other} pod {how}"
+ )
+
+ async def ensure_known(self, side: Side) -> None:
+ """Read a pod's pose if the rail does not know it and a reader is set. Moves nothing."""
+ if side in self.pods and self.occupied(side) is None and side in self.readers:
+ self.update(side, await self.readers[side]())
+
+ @contextlib.asynccontextmanager
+ async def moving(self, side: Side, start: PodPose, end: PodPose) -> AsyncIterator[None]:
+ """Hold a move's swept range for as long as the move runs.
+
+ Checked and reserved together, under one lock. A move that conflicts only with the other
+ pod's move in flight waits for that move to finish, then is checked again. On success the
+ pod's pose becomes `end`. On failure it becomes unknown, but the reservation stays until a
+ pose is read: the pod is somewhere in that range.
+
+ Raises:
+ RailCollisionError, RuntimeError: as `check`, before the move starts.
+ TimeoutError: if the other pod's move does not finish within `WAIT_TIMEOUT`.
+ """
+ other = OTHER[side]
+ await self.ensure_known(other)
+ while True:
+ async with self._lock:
+ swept = self.check(side, start, end)
+ running = (
+ self._reserved.get(other) if other in self.pods and self._in_flight(other) else None
+ )
+ if running is None or not g.grid_overlap(swept, running):
+ self._reserved[side] = swept
+ self._end[side] = self.range_at(side, end)
+ self._done[side].clear()
+ break
+ done = self._done[other]
+ logger.info("%s pod waits for the %s pod's move to clear its path", side, other)
+ await asyncio.wait_for(done.wait(), WAIT_TIMEOUT)
+ try:
+ yield
+ except BaseException:
+ self._pose[side] = None
+ raise
+ finally:
+ self._end[side] = None
+ self._done[side].set()
+ self.update(side, end)
diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py
new file mode 100644
index 00000000000..c2809857f57
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py
@@ -0,0 +1,244 @@
+"""The shared X rail: Biomek's pod-against-pod rule with the gripper, the reservations for moves
+in flight, waiting versus refusing, and moves refused before anything is sent."""
+
+import asyncio
+import unittest
+from typing import Optional
+
+from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g
+from pylabrobot.beckman_coulter.biomek_i7.driver.homing_tests import SimulatedRunTest
+from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration
+
+CONFIG = generic_configuration()
+LEFT, RIGHT = CONFIG.pod("left"), CONFIG.pod("right")
+PODS = {"left": LEFT, "right": RIGHT}
+PARK_GG = 7.889 # the park's grip width, cm
+PLATE = g.HeldLabware(length=12.776, width=8.548) # an SBS plate, held lengthwise
+
+
+def pose(side: str, counts: int, gr: Optional[float] = 0.0, held=None) -> PodPose:
+ """A pod at X `counts`, its gripper turned to `gr` degrees (None: not known)."""
+ gripper = None if gr is None else g.GripperPose(gr, PARK_GG, held)
+ return PodPose(PODS[side].to_value("X", counts), gripper)
+
+
+def rail() -> XRail:
+ return XRail({"left": LEFT, "right": RIGHT})
+
+
+class PodGeometryTests(unittest.TestCase):
+ def test_the_pipettor_lies_inside_the_bridge(self) -> None:
+ for pod in (LEFT, RIGHT):
+ self.assertEqual(g.pod_x_range(pod.geometry, 50.0), g.bridge_x_range(pod.geometry, 50.0))
+
+ def test_a_box_turning_covers_every_angle_between(self) -> None:
+ box = (1.0, 2.0, 0.0, 0.0)
+ self.assertEqual(g.turned_x_extent(box, 0, 0), (1.0, 2.0))
+ lo, hi = g.turned_x_extent(box, 180, 180)
+ self.assertAlmostEqual(lo, -2.0)
+ self.assertAlmostEqual(hi, -1.0)
+ lo, hi = g.turned_x_extent(box, 0, 180)
+ self.assertAlmostEqual(lo, -2.0)
+ self.assertAlmostEqual(hi, 2.0)
+
+ def test_the_right_gripper_reaches_past_its_bridge_towards_the_left_pod(self) -> None:
+ model = g.GripperModel.from_bif(RIGHT.gripper_model)
+ bridge = g.bridge_x_range(RIGHT.geometry, 100.0)
+ facing_left = g.gripper_x_range(RIGHT.geometry, model, 100.0, g.GripperPose(180, PARK_GG))
+ self.assertAlmostEqual(bridge[0] - facing_left[0], 9.2, 1)
+ holding = g.gripper_x_range(RIGHT.geometry, model, 100.0, g.GripperPose(180, PARK_GG, PLATE))
+ self.assertLess(holding[0], facing_left[0] - 4) # the plate sticks out past the fingers
+
+ def test_the_left_gripper_never_reaches_past_its_bridge_towards_the_right_pod(self) -> None:
+ model = g.GripperModel.from_bif(LEFT.gripper_model)
+ low, high = LEFT.limits["GR"]
+ reach = g.gripper_x_range(
+ LEFT.geometry,
+ model,
+ 100.0,
+ g.GripperPose(low, 15.681, PLATE),
+ g.GripperPose(high, 15.681, PLATE),
+ )
+ self.assertLess(reach[1], g.bridge_x_range(LEFT.geometry, 100.0)[1])
+
+ def test_a_turn_is_swept_along_its_path(self) -> None:
+ model = g.GripperModel.from_bif(RIGHT.gripper_model)
+ a, b = (
+ g.Gripper(model, g.GripperPose(90, PARK_GG)),
+ g.Gripper(model, g.GripperPose(-90, PARK_GG)),
+ )
+ swept = g.swept_x_range(RIGHT.geometry, 100.0, 100.0, a, b)
+ at_zero = g.gripper_x_range(RIGHT.geometry, model, 100.0, g.GripperPose(0, PARK_GG))
+ self.assertGreaterEqual(swept[1], at_zero[1]) # passes through 0 degrees on the way
+
+
+class RailTests(unittest.IsolatedAsyncioTestCase):
+ def test_the_bridges_meet_one_grid_cell_short_of_touching(self) -> None:
+ """The right gripper facing right (GR 0) stays inside its bridge: the bridges decide. They
+ touch at a combined 250,807 counts; Biomek compares edges as 1/16 cm cells, so with the
+ right pod here the last move allowed is a combined 250,767."""
+ r = rail()
+ r.update("right", pose("right", -9258))
+ r.check("left", pose("left", 0), pose("left", 241420)) # Biomek's own move
+ r.check("left", pose("left", 0), pose("left", 250767 - 9258))
+ with self.assertRaises(RailCollisionError):
+ r.check("left", pose("left", 0), pose("left", 250768 - 9258))
+ with self.assertRaises(RailCollisionError): # touching, and in the same cell
+ r.check("left", pose("left", 0), pose("left", 250807 - 9258))
+
+ def test_the_parked_right_gripper_takes_the_left_pod_closer_in(self) -> None:
+ """Parked facing the front (GR 90), the right gripper reaches 0.86 cm past its bridge."""
+ r = rail()
+ r.update("right", pose("right", -9258, gr=90))
+ with self.assertRaises(RailCollisionError):
+ r.check("left", pose("left", 0), pose("left", 250807 - 9258))
+ r.check("left", pose("left", 0), pose("left", 250807 - 9258 - 2300))
+
+ def test_turning_the_gripper_into_the_other_pod_is_refused(self) -> None:
+ r = rail()
+ r.update("left", pose("left", int((70 - 10.519) * 2560))) # deck X 70: bridge to 93.6
+ right_x = int((110 - 146.40669375) * 2560) # deck X 110: bridge from 95.7
+ r.check("right", pose("right", right_x, gr=0), pose("right", right_x, gr=0))
+ with self.assertRaises(RailCollisionError):
+ r.check("right", pose("right", right_x, gr=0), pose("right", right_x, gr=180))
+
+ def test_an_unknown_gripper_pose_counts_every_pose(self) -> None:
+ r = rail()
+ right_x = int((110 - 146.40669375) * 2560)
+ r.update("right", pose("right", right_x, gr=None))
+ with self.assertRaises(RailCollisionError): # it could be facing left
+ r.check("left", pose("left", 0), pose("left", int((70 - 10.519) * 2560)))
+
+ def test_either_pod_is_checked(self) -> None:
+ # Counts run from each pod's own home: the right pod's -2,560 is its park at the right end.
+ r = rail()
+ r.update("left", pose("left", 241420))
+ r.check("right", pose("right", -2560), pose("right", 241420 - 250717))
+ with self.assertRaises(RailCollisionError):
+ r.check("right", pose("right", -2560), pose("right", 241420 - 250718))
+
+ def test_a_pod_cannot_pass_through_the_other(self) -> None:
+ r = rail()
+ r.update("left", pose("left", 100000))
+ with self.assertRaises(RailCollisionError):
+ r.check("right", pose("right", -2560), pose("right", -230000))
+
+ async def test_crossing_only_a_running_move_waits_for_it(self) -> None:
+ r = rail()
+ r.update("left", pose("left", 200000)) # far over; retreating home
+ r.update("right", pose("right", -2560))
+ order = []
+
+ async def right_moves() -> None:
+ async with r.moving("right", pose("right", -2560), pose("right", -60000)):
+ order.append("right")
+
+ async with r.moving("left", pose("left", 200000), pose("left", 0)):
+ task = asyncio.create_task(right_moves())
+ await asyncio.sleep(0)
+ order.append("left")
+ await task
+ self.assertEqual(order, ["left", "right"])
+
+ async def test_crossing_where_a_running_move_ends_is_refused(self) -> None:
+ r = rail()
+ r.update("left", pose("left", 0))
+ r.update("right", pose("right", -2560))
+ async with r.moving("left", pose("left", 0), pose("left", 200000)):
+ with self.assertRaises(RailCollisionError):
+ async with r.moving("right", pose("right", -2560), pose("right", -60000)):
+ pass
+
+ async def test_a_read_coming_back_mid_move_keeps_the_reservation(self) -> None:
+ r = rail()
+ r.update("left", pose("left", 0))
+ r.update("right", pose("right", -2560))
+ async with r.moving("right", pose("right", -2560), pose("right", -150000)):
+ r.update("right", pose("right", -2560))
+ with self.assertRaises(RailCollisionError):
+ r.check("left", pose("left", 0), pose("left", 150000))
+
+ async def test_a_failed_move_keeps_its_reservation_until_read(self) -> None:
+ r = rail()
+ r.update("left", pose("left", 0))
+ r.update("right", pose("right", -2560))
+ with self.assertRaises(OSError):
+ async with r.moving("left", pose("left", 0), pose("left", 200000)):
+ raise OSError("lost the board")
+ self.assertEqual(r.occupied("left"), r.swept("left", pose("left", 0), pose("left", 200000)))
+ r.update("left", pose("left", 150000))
+ self.assertEqual(r.occupied("left"), r.range_at("left", pose("left", 150000)))
+
+ def test_an_unknown_position_allows_only_moving_away(self) -> None:
+ r = rail()
+ r.update("left", pose("left", 100000))
+ r.check("left", pose("left", 100000), pose("left", 50000))
+ with self.assertRaisesRegex(RuntimeError, "not known"):
+ r.check("left", pose("left", 100000), pose("left", 120000))
+
+ async def test_an_unknown_position_is_read_first(self) -> None:
+ r = rail()
+ r.update("left", pose("left", 0))
+
+ async def read_right() -> PodPose:
+ return pose("right", -2560)
+
+ r.readers["right"] = read_right
+ async with r.moving("left", pose("left", 0), pose("left", 100000)):
+ pass
+ self.assertIsNotNone(r.occupied("right"))
+
+ def test_no_declared_geometry_no_moves(self) -> None:
+ r = XRail({"left": LEFT, "right": None})
+ with self.assertRaisesRegex(RuntimeError, "no declared geometry"):
+ r.check("left", pose("left", 0), pose("left", 1000))
+
+ def test_a_lone_pod_is_free(self) -> None:
+ XRail({"left": LEFT}).check("left", pose("left", 0), pose("left", 300000))
+
+
+class RailOnTheInstrumentTests(SimulatedRunTest):
+ async def test_a_move_into_the_other_pod_sends_no_motion(self) -> None:
+ driver = await self.start(True)
+ await driver.home()
+ assert driver.left_x_arm and driver.right_x_arm
+ await driver.right_x_arm.move_axes({"X": -100000})
+ self.mark(driver)
+ with self.assertRaises(RailCollisionError):
+ await driver.left_x_arm.move_axes({"X": 200000})
+ sent = {m[4] for m in self.usb(driver, "multichannel").requests[self.marks["multichannel"] :]}
+ self.assertNotIn(0x40, sent) # no Set Move Parameters
+ self.assertNotIn(0x50, sent) # no Move All
+ await driver.left_x_arm.move_axes({"X": 140000})
+ self.assertEqual(driver.left_x_arm.cpositions["X"], (140000, 140000))
+
+ async def test_turning_a_gripper_into_the_other_pod_sends_no_motion(self) -> None:
+ driver = await self.start(True)
+ await driver.home()
+ assert driver.left_x_arm and driver.right_x_arm
+ left, right = driver.left_x_arm, driver.right_x_arm
+ await left.move_axes({"X": int((70 - 10.519) * 2560)})
+ await right.move_axes({"X": int((110 - 146.40669375) * 2560)})
+ facing_left = RIGHT.to_counts("GR", 180.0)
+ self.mark(driver)
+ with self.assertRaises(RailCollisionError):
+ await right.move_axes({"GR": facing_left})
+ sent = {m[4] for m in self.usb(driver, "span8").requests[self.marks["span8"] :]}
+ self.assertNotIn(0x40, sent)
+ self.assertNotIn(0x50, sent)
+
+ async def test_both_pods_moving_at_once_cannot_cross(self) -> None:
+ driver = await self.start(True)
+ await driver.home()
+ assert driver.left_x_arm and driver.right_x_arm
+ results = await asyncio.gather(
+ driver.left_x_arm.move_axes({"X": 150000}),
+ driver.right_x_arm.move_axes({"X": -150000}),
+ return_exceptions=True,
+ )
+ self.assertEqual(sum(isinstance(r, RailCollisionError) for r in results), 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/session_log.py b/pylabrobot/beckman_coulter/biomek_i7/session_log.py
new file mode 100644
index 00000000000..3bca1a33eb8
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/session_log.py
@@ -0,0 +1,88 @@
+"""A run's log in a file of its own, to compare a live run with Biomek's logs of the same work.
+
+`start_session_log(directory)` writes every line of this package's loggers to
+`/biomek_i7_.log`: the driver's commands, warnings and errors, and with
+`usb_frames` every message to and from the boards, unframed and in
+hex, which is what Biomek's Master Controller keeps in its `ace_io` table. Each line starts with
+the time in milliseconds since the epoch, as the Master Controller's tables stamp theirs.
+
+PyLabRobot's own `pylabrobot.setup_logger` writes one file per day for every PyLabRobot logger;
+this one is per run and holds only the Biomek i7's lines, so one run reads on its own.
+"""
+
+import datetime
+import logging
+from pathlib import Path
+from typing import Optional, Union
+
+PACKAGE_LOGGER = "pylabrobot.beckman_coulter.biomek_i7"
+LINE_FORMAT = "%(created_ms)d %(asctime)s.%(msecs)03d %(name)s %(levelname)s %(message)s"
+DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
+
+
+class _EpochMilliseconds(logging.Formatter):
+ def format(self, record: logging.LogRecord) -> str:
+ record.created_ms = int(record.created * 1000)
+ return super().format(record)
+
+
+class SessionLog:
+ """A session log being written; `stop()` closes it."""
+
+ def __init__(self, path: Path, handler: logging.Handler):
+ self.path = path
+ self._handler = handler
+
+ def stop(self) -> None:
+ """Stop writing the log and close its file."""
+ logging.getLogger(PACKAGE_LOGGER).removeHandler(self._handler)
+ self._handler.close()
+
+ def __enter__(self) -> "SessionLog":
+ return self
+
+ def __exit__(self, *exc) -> None:
+ self.stop()
+
+
+def start_session_log(
+ directory: Union[str, Path],
+ usb_frames: bool = True,
+ name: Optional[str] = None,
+) -> SessionLog:
+ """Start writing this package's log lines to a new timestamped file in `directory`.
+
+ The package's loggers are set to log at DEBUG (with `usb_frames`) or INFO, and any of its
+ loggers set higher is reset to follow the package's level, so every line reaches the file. What
+ a console shows is up to the console's own handler and its level.
+
+ Args:
+ directory: where to write the log; made if missing.
+ usb_frames: also write every message to and from the boards (DEBUG lines ` write `
+ and ` read `).
+ name: the file's name; default `biomek_i7_.log`.
+
+ Returns:
+ The log being written; `.path` is its file.
+ """
+ directory = Path(directory)
+ directory.mkdir(parents=True, exist_ok=True)
+ stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
+ path = directory / (name or f"biomek_i7_{stamp}.log")
+ handler = logging.FileHandler(path, encoding="utf-8")
+ handler.setLevel(logging.NOTSET)
+ handler.setFormatter(_EpochMilliseconds(LINE_FORMAT, DATE_FORMAT))
+
+ level = logging.DEBUG if usb_frames else logging.INFO
+ package = logging.getLogger(PACKAGE_LOGGER)
+ package.setLevel(level)
+ for logger_name, logger in logging.root.manager.loggerDict.items():
+ if (
+ logger_name.startswith(PACKAGE_LOGGER + ".")
+ and isinstance(logger, logging.Logger)
+ and logger.level > level
+ ):
+ logger.setLevel(logging.NOTSET)
+ package.addHandler(handler)
+ package.info("session log started: %s (USB frames %s)", path, "on" if usb_frames else "off")
+ return SessionLog(path, handler)
diff --git a/pylabrobot/beckman_coulter/biomek_i7/session_log_tests.py b/pylabrobot/beckman_coulter/biomek_i7/session_log_tests.py
new file mode 100644
index 00000000000..d91626bd110
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/session_log_tests.py
@@ -0,0 +1,49 @@
+"""A session log holds the driver's commands and, at DEBUG, every message to and from the boards."""
+
+import asyncio
+import re
+import tempfile
+import unittest
+from pathlib import Path
+
+from pylabrobot.beckman_coulter.biomek_i7.session_log import start_session_log
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import (
+ generic_driver,
+ generic_simulated_boards,
+)
+
+
+class SessionLogTests(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self) -> None:
+ asyncio.get_running_loop().set_debug(False)
+
+ async def run_setup(self) -> None:
+ driver = generic_driver(generic_simulated_boards()) # just powered up: configured at setup
+ await driver.setup()
+ await driver.stop()
+
+ async def test_a_run_is_logged_with_its_frames(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ log = start_session_log(directory)
+ try:
+ await self.run_setup()
+ finally:
+ log.stop()
+ lines = Path(log.path).read_text(encoding="utf-8").splitlines()
+ self.assertTrue(Path(log.path).name.startswith("biomek_i7_"))
+ self.assertTrue(all(re.match(r"\d{13} ", line) for line in lines))
+ self.assertTrue(any(" MC_1 configure" in line for line in lines))
+ self.assertTrue(any(re.search(r" write [0-9a-f]+$", line) for line in lines))
+ self.assertTrue(any(re.search(r" read [0-9a-f]+$", line) for line in lines))
+
+ async def test_info_only_leaves_out_the_frames(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ with start_session_log(directory, usb_frames=False) as log:
+ await self.run_setup()
+ text = Path(log.path).read_text(encoding="utf-8")
+ self.assertIn(" SPAN8_2 configure", text)
+ self.assertNotIn(" write ", text)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py
new file mode 100644
index 00000000000..703e6e8b87a
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py
@@ -0,0 +1,114 @@
+"""What the package's tests build their simulated Biomek i7 from: the generic one in `defaults/`,
+named explicitly (never through `$BIOMEK_I7_SIMULATOR_RECORDING`). Not a test module itself."""
+
+import atexit
+import copy
+import json
+import shutil
+import tempfile
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Sequence
+
+from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_CONFIGURATION, GENERIC_RECORDING
+from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard
+from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration
+from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver
+from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB, simulated_boards
+
+_GENERIC: Optional[Dict[str, Any]] = None
+
+# The serial numbers the generic cold start answers: placeholders as long as real ones.
+GENERIC_SERIAL_NUMBERS = {
+ "chassis": "SIMULATED00100000000000000000000",
+ "left": "SIMULATED00200000000000000000000",
+ "right": "SIMULATED00900000000000000000000",
+}
+
+
+def generic_recording() -> Dict[str, Any]:
+ """The generic cold-start recording, a fresh copy a test may change: `boards` maps each module
+ (`chassis`, `multichannel`, `span8`) to its [request key, [replies]] pairs."""
+ global _GENERIC
+ if _GENERIC is None:
+ with open(GENERIC_RECORDING, encoding="utf-8") as fh:
+ _GENERIC = json.load(fh)
+ return copy.deepcopy(_GENERIC)
+
+
+def generic_boards(
+ recording: Optional[Dict[str, Any]] = None,
+ modules: Optional[Sequence[str]] = None,
+ default_timeout: float = 1.0,
+) -> List[AceBoard]:
+ """A replayed board per module of `recording` (by default the generic one), as
+ `simulator.replay_boards` builds them; `modules` picks and orders them."""
+ data = recording if recording is not None else generic_recording()
+ names = list(data["boards"]) if modules is None else list(modules)
+ return [
+ AceBoard(
+ io=ReplayAceUSB(dict(data["boards"][module]), name=f"replayed {module}"),
+ name=f"replayed {module}",
+ default_timeout=default_timeout,
+ )
+ for module in names
+ ]
+
+
+def generic_configuration() -> DeviceConfiguration:
+ """The generic declared configuration, loaded afresh (a test may change its copy)."""
+ return DeviceConfiguration.load(GENERIC_CONFIGURATION)
+
+
+def sealed(configuration: DeviceConfiguration) -> DeviceConfiguration:
+ """A test's changed copy, with its fingerprints recorded again so that it loads. Only tests do
+ this: the package makes a configuration from Biomek's files, never from another."""
+ configuration.sources = {
+ name: {**configuration.sources.get(name, {}), "fingerprint": f}
+ for name, f in configuration.fingerprints().items()
+ }
+ return configuration
+
+
+def as_instrument(configuration: DeviceConfiguration) -> DeviceConfiguration:
+ """`configuration` as the generic instrument's own: not generic, and naming the serial numbers
+ its cold start answers (sealed)."""
+ configuration.generic = False
+ configuration.chassis_serial_number = GENERIC_SERIAL_NUMBERS["chassis"]
+ for side, pod in configuration.pods.items():
+ pod.module_serial_number = GENERIC_SERIAL_NUMBERS[side]
+ return sealed(configuration)
+
+
+def configuration_file(configuration: DeviceConfiguration) -> str:
+ """`configuration` saved to a new temporary file, for `declared_configuration_json`; removed
+ when the tests end."""
+ folder = Path(tempfile.mkdtemp(prefix="biomek_i7_test_"))
+ atexit.register(shutil.rmtree, folder, ignore_errors=True)
+ path = folder / "configuration.json"
+ configuration.save(path)
+ return str(path)
+
+
+def generic_simulated_boards(**kwargs: Any) -> List[AceBoard]:
+ """The generic instrument simulated (`simulator.simulated_boards`), with the generic
+ configuration's motor tables and the generic cold start; `kwargs` as `simulated_boards` takes
+ them (`homed`, `configured`)."""
+ kwargs.setdefault("path", GENERIC_RECORDING)
+ return simulated_boards(generic_configuration().motor_tables, **kwargs)
+
+
+def generic_driver(
+ boards: Optional[Sequence[AceBoard]] = None,
+ configuration: Optional[DeviceConfiguration] = None,
+ **kwargs: Any,
+) -> BiomekI7Driver:
+ """A driver over `boards` (by default the generic instrument replayed), declared by
+ `configuration` (by default the generic configuration's file); `kwargs` as `BiomekI7Driver`
+ takes them."""
+ return BiomekI7Driver(
+ declared_configuration_json=(
+ str(GENERIC_CONFIGURATION) if configuration is None else configuration_file(configuration)
+ ),
+ boards=generic_boards() if boards is None else boards,
+ **kwargs,
+ )
diff --git a/pylabrobot/beckman_coulter/biomek_i7/units.py b/pylabrobot/beckman_coulter/biomek_i7/units.py
new file mode 100644
index 00000000000..0372726e99a
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/units.py
@@ -0,0 +1,222 @@
+"""Where PyLabRobot's units meet Biomek's: the one place they are converted.
+
+The public API takes and returns PyLabRobot's units: mm, mm/s, uL, uL/s, s, deg, in the deck's
+frame (Y towards the back). Biomek works in its own, and so does the driver's planning (the
+plans, the recipes): cm, its frame (X to the right, Y
+towards the front), and a speed field, per mille of each axis's maximum velocity (1..1000). A
+public method converts its arguments here once and hands them to its Biomek-unit counterpart;
+nothing inside converts back and forth, so a run is the same request for request.
+
+Imports nothing of the package's, so every layer can use it.
+"""
+
+import math
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Optional, Tuple
+
+from pylabrobot.resources.coordinate import Coordinate
+
+if TYPE_CHECKING:
+ from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod
+
+MM_PER_CM = 10.0
+
+# The deck's frame against Biomek's, chosen rather than measured: its left edge 10 cm left of
+# Biomek's X origin, clear of the left trash bin, and its front edge 70 cm in front of Biomek's Y
+# origin, clear of the front row of ALPs. x = X + FRAME_X, y = FRAME_Y - Y (mm).
+FRAME_X = 10.0 * MM_PER_CM
+FRAME_Y = 70.0 * MM_PER_CM
+
+FULL_SPEED = 1000
+"""The speed field's top: the axis's maximum velocity."""
+
+
+# -- lengths ---------------------------------------------------------------------------------------
+
+
+def cm(value: float) -> float:
+ """A length Biomek states in centimetres, in millimetres.
+
+ Every dimension transcribed from a Biomek definition goes through here, written as Biomek states
+ it, so the literal in the code can be compared against its source as it stands.
+ """
+ return value * MM_PER_CM
+
+
+def to_cm(mm: float) -> float:
+ """A length in mm, in Biomek's cm."""
+ return mm / MM_PER_CM
+
+
+def optional_cm(mm: Optional[float]) -> Optional[float]:
+ """`to_cm`, passing None through (an argument left to its default)."""
+ return None if mm is None else to_cm(mm)
+
+
+def to_mm(cm_value: float) -> float:
+ """A length in Biomek's cm, in mm."""
+ return cm_value * MM_PER_CM
+
+
+# -- the frame -------------------------------------------------------------------------------------
+
+
+def biomek_x(x: float) -> float:
+ """A deck x, in mm, as Biomek's X in mm."""
+ return x - FRAME_X
+
+
+def biomek_y(y: float) -> float:
+ """A deck y, in mm, as Biomek's Y in mm (the flip is its own inverse: `deck_y`)."""
+ return FRAME_Y - y
+
+
+def deck_x(x: float) -> float:
+ """Biomek's X, in mm, as a deck x in mm."""
+ return x + FRAME_X
+
+
+deck_y = biomek_y
+"""Biomek's Y, in mm, as a deck y in mm."""
+
+
+@dataclass(frozen=True)
+class BiomekPoint:
+ """A point in Biomek's frame, cm: X to the right, Y towards the front, Z up from the deck."""
+
+ x: float
+ y: float
+ z: float
+
+
+def to_biomek(point: Coordinate) -> BiomekPoint:
+ """A deck coordinate (mm, PyLabRobot's frame) in Biomek's frame (cm)."""
+ return BiomekPoint(
+ biomek_x(point.x) / MM_PER_CM, biomek_y(point.y) / MM_PER_CM, point.z / MM_PER_CM
+ )
+
+
+def offset_to_biomek(x: float, y: float, offset: Coordinate) -> Tuple[float, float]:
+ """Biomek X/Y (cm) moved by a PyLabRobot `offset` (mm): Biomek's Y runs to the front."""
+ return x + offset.x / MM_PER_CM, y - offset.y / MM_PER_CM
+
+
+# -- axis values -----------------------------------------------------------------------------------
+
+
+def _is_y(axis: str) -> bool:
+ return axis == "GY" or (axis[0] == "Y" and (len(axis) == 1 or axis[1:].isdigit()))
+
+
+def axis_to_biomek(axis: str, value: float) -> float:
+ """An axis's target in PyLabRobot's units as Biomek's value for it:
+ - X, Y, Y1-Y8, GY: a deck x / y, mm, in Biomek's frame, cm;
+ - Z, Z1-Z8, GZ (mm above the deck), GG, S (mm): cm;
+ - GR: degrees counterclockwise from +X seen from above (PyLabRobot's), as Biomek's, which turn
+ the other way (its 90 points the fingers to the front);
+ - the pumps (D, D1-D8): uL, as Biomek's.
+ """
+ if axis == "X":
+ return to_cm(biomek_x(value))
+ if _is_y(axis):
+ return to_cm(biomek_y(value))
+ if axis == "GR":
+ return -value
+ if axis[0] == "D":
+ return value
+ return to_cm(value)
+
+
+def axis_from_biomek(axis: str, value: float) -> float:
+ """`axis_to_biomek`'s inverse."""
+ if axis == "X":
+ return deck_x(to_mm(value))
+ if _is_y(axis):
+ return deck_y(to_mm(value))
+ if axis == "GR":
+ return -value
+ if axis[0] == "D":
+ return value
+ return to_mm(value)
+
+
+def axis_to_counts(pod: "Pod", axis: str, value: float) -> int:
+ """An axis's target in PyLabRobot's units (`axis_to_biomek`) in counts."""
+ declared = pod.declared
+ if declared is None:
+ raise RuntimeError(f"{pod} has no declared configuration")
+ return declared.to_counts(axis, axis_to_biomek(axis, value))
+
+
+def counts_to_axis(pod: "Pod", axis: str, counts: int) -> float:
+ """An axis's position in counts in PyLabRobot's units (`axis_from_biomek`)."""
+ declared = pod.declared
+ if declared is None:
+ raise RuntimeError(f"{pod} has no declared configuration")
+ return axis_from_biomek(axis, declared.to_value(axis, counts))
+
+
+# -- speeds ----------------------------------------------------------------------------------------
+
+
+def percent_to_field(percent: float, truncate: bool = False) -> int:
+ """A speed Biomek states in percent of an axis's maximum, as the speed field, 1..1000. Biomek
+ rounds, except where it truncates (`truncate`: the Span-8 prime's `D1SpeedLimit`, 80.17 %, is
+ the logged 801)."""
+ field = int(percent * 10) if truncate else round(percent * 10)
+ return max(1, min(FULL_SPEED, field))
+
+
+def _per_unit(pod: "Pod", axis: str) -> float:
+ """Counts per PyLabRobot unit of `axis` (per mm, deg or uL)."""
+ declared = pod.declared
+ if declared is None:
+ raise RuntimeError(f"{pod} has no declared configuration")
+ conversion = declared.conversion[axis]
+ return abs(conversion.const) / (MM_PER_CM if conversion.unit == "cm" else 1.0)
+
+
+def max_rate(pod: "Pod", axis: str) -> float:
+ """`axis`'s maximum velocity in PyLabRobot units per second (mm/s, deg/s, uL/s)."""
+ return pod.axis(axis).limits.max_velocity / _per_unit(pod, axis)
+
+
+def rate_to_field(pod: "Pod", axis: str, rate: float, clamp: bool = False) -> int:
+ """The speed field that moves `axis` at `rate` PyLabRobot units per second (mm/s, deg/s, uL/s):
+ its peak velocity; the move's acceleration scales with it, as the instrument has one speed per
+ move.
+
+ Raises:
+ ValueError: for a rate not above 0, or above the axis's maximum (unless `clamp`, which takes
+ it to 1..1000).
+ """
+ field = round(rate * _per_unit(pod, axis) / pod.axis(axis).limits.max_velocity * FULL_SPEED)
+ if clamp:
+ return max(1, min(FULL_SPEED, field))
+ if not rate > 0 or field > FULL_SPEED:
+ raise ValueError(
+ f"{pod}: {axis} moves at up to {max_rate(pod, axis):.4g} per second, not {rate}"
+ )
+ return max(1, field)
+
+
+def field_to_rate(pod: "Pod", axis: str, field: int) -> float:
+ """The rate (PyLabRobot units per second) the speed field `field` moves `axis` at."""
+ return field / FULL_SPEED * max_rate(pod, axis)
+
+
+def fraction_to_field(fraction: float) -> int:
+ """A speed as a fraction of each axis's maximum, (0, 1], as the speed field: for a move of
+ several axes, whose maxima differ, so that no single rate describes it.
+
+ Raises:
+ ValueError: outside (0, 1].
+ """
+ if not 0 < fraction <= 1 or math.isnan(fraction):
+ raise ValueError(f"a speed fraction is above 0 and at most 1, not {fraction}")
+ return max(1, round(fraction * FULL_SPEED))
+
+
+def cutoff_to_counts(pod: "Pod", axis: str, rate: float) -> int:
+ """A pump's cutoff velocity, uL/s, in counts/s."""
+ return round(rate * _per_unit(pod, axis))
diff --git a/pylabrobot/beckman_coulter/biomek_i7/units_tests.py b/pylabrobot/beckman_coulter/biomek_i7/units_tests.py
new file mode 100644
index 00000000000..9de769f9d66
--- /dev/null
+++ b/pylabrobot/beckman_coulter/biomek_i7/units_tests.py
@@ -0,0 +1,83 @@
+"""The one place PyLabRobot's units meet Biomek's (`units.py`): exact where Biomek's logs are."""
+
+import asyncio
+import unittest
+
+from pylabrobot.beckman_coulter.biomek_i7 import units as u
+from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_driver
+from pylabrobot.resources.coordinate import Coordinate
+
+
+class LengthAndFrameTests(unittest.TestCase):
+ def test_lengths_and_the_frame_round_trip(self) -> None:
+ for mm in (0.0, 1.0, 123.456, -7.5):
+ self.assertAlmostEqual(u.to_mm(u.to_cm(mm)), mm)
+ self.assertAlmostEqual(u.deck_x(u.biomek_x(mm)), mm)
+ self.assertAlmostEqual(u.deck_y(u.biomek_y(mm)), mm)
+ self.assertIsNone(u.optional_cm(None))
+ point = u.to_biomek(Coordinate(100.0, 700.0, 25.0))
+ self.assertEqual(point, u.BiomekPoint(0.0, 0.0, 2.5)) # the frame's origin, 2.5 cm up
+
+ def test_an_offset_turns_with_biomeks_y(self) -> None:
+ self.assertEqual(u.offset_to_biomek(10.0, 20.0, Coordinate(5.0, 5.0, 0)), (10.5, 19.5))
+
+ def test_percent_is_biomeks_rounding_or_truncation(self) -> None:
+ self.assertEqual(u.percent_to_field(25), 250)
+ self.assertEqual(u.percent_to_field(80.1724), 802)
+ self.assertEqual(u.percent_to_field(80.1724, truncate=True), 801) # the logged prime speed
+ self.assertEqual(u.percent_to_field(0.01), 1)
+ self.assertEqual(u.percent_to_field(150), 1000)
+
+ def test_a_fraction_is_refused_outside_zero_to_one(self) -> None:
+ self.assertEqual(u.fraction_to_field(1.0), 1000)
+ self.assertEqual(u.fraction_to_field(0.25), 250)
+ for bad in (0.0, 1.01, -0.5, float("nan")):
+ with self.assertRaises(ValueError):
+ u.fraction_to_field(bad)
+
+
+class RateTests(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self) -> None:
+ asyncio.get_running_loop().set_debug(False)
+ self.driver = generic_driver()
+ await self.driver.discover()
+ self.addAsyncCleanup(self.driver.stop)
+
+ def axes(self):
+ for pod in self.driver.arms:
+ assert pod.declared is not None
+ for axis in pod.axes:
+ if axis.name in pod.declared.conversion and (axis.name[0] in "ZD" or axis.name == "GZ"):
+ yield pod, axis.name
+
+ def test_every_field_round_trips_on_every_z_and_pump(self) -> None:
+ checked = 0
+ for pod, axis in self.axes():
+ for field in range(1, 1001):
+ rate = u.field_to_rate(pod, axis, field)
+ self.assertEqual(u.rate_to_field(pod, axis, rate), field, f"{pod} {axis} {field}")
+ checked += 1
+ self.assertGreaterEqual(checked, 20 * 1000) # Z, D, GZ; Z1-Z8, D1-D8, GZ
+
+ def test_a_rate_above_the_maximum_is_refused_naming_it(self) -> None:
+ left = self.driver.left_x_arm
+ assert left is not None
+ top = u.max_rate(left, "Z")
+ self.assertAlmostEqual(top, 95.0) # mm/s: the Multichannel Z, 24320 counts/s at 2560 /cm
+ with self.assertRaisesRegex(ValueError, "Z moves at up to 95"):
+ u.rate_to_field(left, "Z", 125.0) # the STAR's default z speed
+ with self.assertRaises(ValueError):
+ u.rate_to_field(left, "Z", 0.0)
+ self.assertEqual(u.rate_to_field(left, "Z", 125.0, clamp=True), 1000)
+
+ def test_the_flow_rate_is_the_old_plunger_arithmetic(self) -> None:
+ left = self.driver.left_x_arm
+ assert left is not None and left.declared is not None
+ for flow in (1.0, 50.0, 90.0, 100.0, 150.0, 400.0, 2000.0):
+ per_second = flow * left.declared.conversion["D"].const
+ old = max(1, min(1000, round(per_second / left.axis("D").limits.max_velocity * 1000)))
+ self.assertEqual(u.rate_to_field(left, "D", flow, clamp=True), old)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/io/usb.py b/pylabrobot/io/usb.py
index d8028dbf8ee..8f8b98b524a 100644
--- a/pylabrobot/io/usb.py
+++ b/pylabrobot/io/usb.py
@@ -351,7 +351,9 @@ def get_available_devices(self) -> List["usb.core.Device"]:
continue
if self._serial_number is not None:
- if dev._serial_number is None:
+ # PyUSB reads the serial number descriptor on first access; `_serial_number` is only its
+ # cache, empty until then.
+ if dev.iSerialNumber == 0 or dev.serial_number is None:
raise RuntimeError(
f"A serial number was specified for '{self.human_readable_device_name}', but the device does not have a serial number."
)
diff --git a/pylabrobot/io/usb_tests.py b/pylabrobot/io/usb_tests.py
index 358d1f12ad5..c8ab3787f12 100644
--- a/pylabrobot/io/usb_tests.py
+++ b/pylabrobot/io/usb_tests.py
@@ -189,3 +189,28 @@ def test_validator_replays_a_write(self) -> None:
]
validator = USBValidator(capture, "mock USB", 1, 2)
self.assertEqual(validator.ctrl_transfer(0x40, 1, 0, 0, b"\x01"), bytearray())
+
+
+class USBDeviceSelectionTests(unittest.TestCase):
+ """Pick a device by serial number, reading the descriptor rather than PyUSB's empty cache."""
+
+ def _devices(self, *serials):
+ devices = []
+ for serial in serials:
+ dev = Mock(iSerialNumber=3 if serial else 0, _serial_number=None, serial_number=serial)
+ devices.append(dev)
+ return devices
+
+ def test_serial_number_is_read_through_the_descriptor(self) -> None:
+ devices = self._devices("A", "B")
+ with patch.object(usb_module, "libusb_package", create=True) as lib:
+ lib.find.return_value = devices
+ self.assertEqual(
+ USB(1, 2, "mock USB", serial_number="B").get_available_devices(), [devices[1]]
+ )
+
+ def test_device_without_serial_number_is_refused(self) -> None:
+ with patch.object(usb_module, "libusb_package", create=True) as lib:
+ lib.find.return_value = self._devices(None)
+ with self.assertRaisesRegex(RuntimeError, "does not have a serial number"):
+ USB(1, 2, "mock USB", serial_number="B").get_available_devices()
diff --git a/pylabrobot/resources/__init__.py b/pylabrobot/resources/__init__.py
index 07e878f25eb..00d3176d54e 100644
--- a/pylabrobot/resources/__init__.py
+++ b/pylabrobot/resources/__init__.py
@@ -3,6 +3,7 @@
from .agilent import *
from .alpaqua import *
from .azenta import *
+from .beckman_coulter import *
from .biorad import *
from .boekel import *
from .btx import *
diff --git a/pylabrobot/resources/beckman_coulter/__init__.py b/pylabrobot/resources/beckman_coulter/__init__.py
new file mode 100644
index 00000000000..4d4403ce12c
--- /dev/null
+++ b/pylabrobot/resources/beckman_coulter/__init__.py
@@ -0,0 +1,24 @@
+from .biomek_resource import BiomekTip, BiomekWell, WellSegment
+from .plates import (
+ beckman_coulter_biomek_24_wellplate_square_rb,
+ beckman_coulter_biomek_96_deepwell_square,
+ beckman_coulter_biomek_96_wellplate_flat,
+ beckman_coulter_biomek_96_wellplate_vb,
+ beckman_coulter_biomek_modular_reservoir,
+ beckman_coulter_biomek_reservoir,
+ beckman_coulter_biomek_reservoir_350cb,
+)
+from .tip_racks import (
+ beckman_coulter_biomek_96_tiprack_50uL_filter,
+ beckman_coulter_biomek_96_tiprack_190uL_filter,
+ beckman_coulter_biomek_96_tiprack_230uL,
+ beckman_coulter_biomek_96_tiprack_1025uL_filter,
+ beckman_coulter_biomek_96_tiprack_1070uL,
+)
+from .tips import (
+ beckman_coulter_biomek_tip_50uL_filter,
+ beckman_coulter_biomek_tip_190uL_filter,
+ beckman_coulter_biomek_tip_230uL,
+ beckman_coulter_biomek_tip_1025uL_filter,
+ beckman_coulter_biomek_tip_1070uL,
+)
diff --git a/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py b/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py
new file mode 100644
index 00000000000..9d267dddfc9
--- /dev/null
+++ b/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py
@@ -0,0 +1,204 @@
+"""Beckman Coulter Biomek tips, tip boxes, plates and reservoirs, against the figures of the Biomek
+classes they transcribe (cm there, mm here)."""
+
+import math
+import unittest
+
+from pylabrobot.resources import (
+ BiomekTip,
+ BiomekWell,
+ Plate,
+ Resource,
+ WellSegment,
+ beckman_coulter_biomek_24_wellplate_square_rb,
+ beckman_coulter_biomek_96_deepwell_square,
+ beckman_coulter_biomek_96_tiprack_50uL_filter,
+ beckman_coulter_biomek_96_tiprack_190uL_filter,
+ beckman_coulter_biomek_96_tiprack_230uL,
+ beckman_coulter_biomek_96_tiprack_1025uL_filter,
+ beckman_coulter_biomek_96_tiprack_1070uL,
+ beckman_coulter_biomek_96_wellplate_flat,
+ beckman_coulter_biomek_96_wellplate_vb,
+ beckman_coulter_biomek_modular_reservoir,
+ beckman_coulter_biomek_reservoir,
+ beckman_coulter_biomek_reservoir_350cb,
+ beckman_coulter_biomek_tip_50uL_filter,
+ beckman_coulter_biomek_tip_190uL_filter,
+ beckman_coulter_biomek_tip_230uL,
+ beckman_coulter_biomek_tip_1025uL_filter,
+ beckman_coulter_biomek_tip_1070uL,
+)
+from pylabrobot.resources.tip_rack import StandingTipRack
+
+
+class BiomekTipTests(unittest.TestCase):
+ def test_a_tip_has_its_class_figures(self) -> None:
+ # tipheight, capacity, filtered, coniclength (cm); every class seats 0.775 cm on the mandrel.
+ for make, length, volume, has_filter, cone in (
+ (beckman_coulter_biomek_tip_50uL_filter, 51.359, 50.0, True, 38.227),
+ (beckman_coulter_biomek_tip_190uL_filter, 51.435, 190.0, True, 28.194),
+ (beckman_coulter_biomek_tip_230uL, 51.435, 230.0, False, 28.194),
+ (beckman_coulter_biomek_tip_1025uL_filter, 109.855, 1025.0, True, 19.8374),
+ (beckman_coulter_biomek_tip_1070uL, 109.855, 1070.0, False, 19.8374),
+ ):
+ with self.subTest(make.__name__):
+ tip = make("tip")
+ self.assertIsInstance(tip, BiomekTip)
+ self.assertAlmostEqual(tip.get_size_z(), length)
+ self.assertEqual(tip.maximal_volume, volume)
+ self.assertEqual(tip.has_filter, has_filter)
+ self.assertAlmostEqual(tip.fitting_depth, 7.75)
+ self.assertAlmostEqual(tip.cone_length, cone)
+ self.assertFalse(tip.is_conductive)
+ self.assertEqual(tip.model, make.__name__)
+
+ def test_a_tip_widens_along_its_cone(self) -> None:
+ tip = beckman_coulter_biomek_tip_1070uL("tip") # mintipradius 0.0635, maxtipradius 0.2413 cm
+ self.assertAlmostEqual(tip.radius_at(0), 0.635)
+ self.assertAlmostEqual(tip.radius_at(19.8374 / 2), (0.635 + 2.413) / 2)
+ self.assertAlmostEqual(tip.radius_at(50), 2.413)
+
+ def test_a_tip_reads_back_from_its_serialization(self) -> None:
+ tip = beckman_coulter_biomek_tip_230uL("tip")
+ back = Resource.deserialize(tip.serialize())
+ self.assertIsInstance(back, BiomekTip)
+ self.assertEqual(back, tip)
+ self.assertNotEqual(back, beckman_coulter_biomek_tip_1070uL("tip"))
+
+
+class BiomekTipBoxTests(unittest.TestCase):
+ BOXES = (
+ # make, height, well1xoffset (mm), tip length
+ (beckman_coulter_biomek_96_tiprack_50uL_filter, 55.9, 14.5, 51.359),
+ (beckman_coulter_biomek_96_tiprack_190uL_filter, 55.9, 14.5, 51.435),
+ (beckman_coulter_biomek_96_tiprack_230uL, 55.9, 14.5, 51.435),
+ (beckman_coulter_biomek_96_tiprack_1025uL_filter, 114.1, 14.4, 109.855),
+ (beckman_coulter_biomek_96_tiprack_1070uL, 114.1, 14.4, 109.855),
+ )
+
+ def test_a_box_holds_96_of_its_tips_on_a_9_mm_grid(self) -> None:
+ for make, _, _, tip_length in self.BOXES:
+ with self.subTest(make.__name__):
+ rack = make("rack")
+ self.assertIsInstance(rack, StandingTipRack)
+ self.assertEqual((rack.num_items_x, rack.num_items_y), (12, 8))
+ self.assertTrue(all(spot.has_tip() for spot in rack.get_all_items()))
+ self.assertAlmostEqual(rack.get_item("A1").get_tip().get_size_z(), tip_length)
+ a1 = rack.get_item("A1").get_location_wrt(rack)
+ a2 = rack.get_item("A2").get_location_wrt(rack)
+ b1 = rack.get_item("B1").get_location_wrt(rack)
+ self.assertAlmostEqual(a2.x - a1.x, 9.0)
+ self.assertAlmostEqual(a1.y - b1.y, 9.0)
+
+ def test_tip_a1_stands_where_the_class_puts_it(self) -> None:
+ """A1's centre is `well1xoffset` from the left edge and 1.12 cm from the back edge; the tips'
+ tops are at the box's height, where the head's mandrels meet them."""
+ for make, height, a1_x, _ in self.BOXES:
+ with self.subTest(make.__name__):
+ rack = make("rack")
+ self.assertEqual((rack.get_size_x(), rack.get_size_y()), (127.9, 85.4))
+ self.assertAlmostEqual(rack.get_size_z(), height)
+ centre = rack.get_item("A1").get_location_wrt(rack, "c", "c", "b")
+ self.assertAlmostEqual(centre.x, a1_x)
+ self.assertAlmostEqual(centre.y, 85.4 - 11.2)
+ self.assertAlmostEqual(centre.z, height)
+
+ def test_a_box_is_gripped_below_its_top(self) -> None:
+ # gripperinfo: the pads at its centre, the fingertips 0.23 cm below its bottom.
+ rack = beckman_coulter_biomek_96_tiprack_230uL("rack")
+ point = rack.preferred_pickup_location
+ assert point is not None
+ self.assertAlmostEqual(point.x, 127.9 / 2)
+ self.assertAlmostEqual(point.y, 85.4 / 2)
+ self.assertAlmostEqual(point.z, -2.3)
+
+
+class BiomekPlateTests(unittest.TestCase):
+ def test_a_segment_holds_biomeks_section_volume(self) -> None:
+ # `sectionvolume` (uL) of each segment, from its outline: a cone, a frustum, a rectangular
+ # section, a round bottom (a spherical cap).
+ for make, volumes in (
+ (beckman_coulter_biomek_96_wellplate_vb, (15.6665, 427.2566)),
+ (beckman_coulter_biomek_96_wellplate_flat, (365.708,)),
+ (beckman_coulter_biomek_96_deepwell_square, (133.645, 2282.995)),
+ (beckman_coulter_biomek_24_wellplate_square_rb, (1072.3303, 9248.0)),
+ ):
+ well = make("plate").get_well("A1")
+ assert isinstance(well, BiomekWell)
+ for segment, volume in zip(well.segments, volumes):
+ with self.subTest(make.__name__, volume=volume):
+ self.assertAlmostEqual(segment.volume(segment.height), volume, delta=0.002 * volume)
+
+ def test_the_logged_liquid_level(self) -> None:
+ # 200 uL in Thermo96VB_PP: the 96-head's logged dispense rose 0.567 cm with the liquid.
+ well = beckman_coulter_biomek_96_wellplate_vb("plate").get_well("A1")
+ self.assertAlmostEqual(well.compute_height_from_volume(200), 5.667, delta=0.01)
+ assert isinstance(well, BiomekWell)
+ self.assertAlmostEqual(well.wall_distance(3.67, 0.0), 4.0)
+
+ def test_a_square_well_meets_its_wall_at_the_side(self) -> None:
+ well = beckman_coulter_biomek_96_deepwell_square("plate").get_well("A1")
+ assert isinstance(well, BiomekWell)
+ self.assertAlmostEqual(well.get_size_x(), 8.28)
+ self.assertAlmostEqual(well.wall_distance(20.0, 0.0), 4.14)
+ self.assertAlmostEqual(well.wall_distance(20.0, math.pi / 4), 4.14 * math.sqrt(2))
+
+ def test_a_well_reads_back_from_its_serialization(self) -> None:
+ plate = beckman_coulter_biomek_96_wellplate_vb("plate", with_lid=True)
+ back = Resource.deserialize(plate.serialize())
+ assert isinstance(back, Plate)
+ well = back.get_item("A1")
+ assert isinstance(well, BiomekWell)
+ self.assertEqual(well, plate.get_item("A1"))
+ self.assertEqual(well.segments[0], WellSegment(2.0, 2.735, 2.735, 0.0, 0.0))
+
+ def test_a_lid_sits_where_biomek_seats_it(self) -> None:
+ # Logged: the fingertips 1.000 cm above the plate's bottom for TiterplateLid on Thermo96VB_PP,
+ # and 4.200 cm for the Thomson lid on its plate. The lid covers the plate's footprint.
+ for make, tips_above in (
+ (beckman_coulter_biomek_96_wellplate_vb, 10.0),
+ (beckman_coulter_biomek_24_wellplate_square_rb, 42.0),
+ ):
+ with self.subTest(make.__name__):
+ plate = make("plate", with_lid=True)
+ lid = plate.lid
+ assert lid is not None and lid.location is not None
+ point = lid.preferred_pickup_location
+ assert point is not None
+ self.assertAlmostEqual(lid.location.z + point.z, tips_above)
+ self.assertEqual(
+ (lid.get_size_x(), lid.get_size_y()), (plate.get_size_x(), plate.get_size_y())
+ )
+
+ def test_an_uncentred_seat_moves_the_grip_point(self) -> None:
+ # The Thomson lid's seat is its plate's corner: its centre 0.381 mm left, 1.46 mm back.
+ plate = beckman_coulter_biomek_24_wellplate_square_rb("plate", with_lid=True)
+ lid = plate.lid
+ assert lid is not None and lid.preferred_pickup_location is not None
+ self.assertAlmostEqual(lid.preferred_pickup_location.x - lid.get_size_x() / 2, -0.381)
+ self.assertAlmostEqual(lid.preferred_pickup_location.y - lid.get_size_y() / 2, 1.4605)
+
+ def test_plates_are_gripped_below_their_bottom(self) -> None:
+ plate = beckman_coulter_biomek_96_wellplate_vb("plate")
+ assert plate.preferred_pickup_location is not None
+ self.assertAlmostEqual(plate.preferred_pickup_location.z, -2.3)
+
+
+class BiomekReservoirTests(unittest.TestCase):
+ def test_a_reservoir_section_is_a_box(self) -> None:
+ well = beckman_coulter_biomek_reservoir_350cb("res").get_well("A1")
+ self.assertAlmostEqual(well.compute_volume_from_height(10), 123.8 * 81.5 * 10, delta=0.01)
+ self.assertEqual(well.max_volume, 300000.0)
+
+ def test_reservoirs_have_a_well_per_section(self) -> None:
+ self.assertEqual(len(beckman_coulter_biomek_reservoir("res").children), 1)
+ modular = beckman_coulter_biomek_modular_reservoir("mod")
+ self.assertEqual(len(modular.children), 4)
+ a1 = modular.get_item("A1")
+ self.assertAlmostEqual(a1.get_size_x(), 23.65) # x1 1.105 to x2 3.47 cm
+ assert isinstance(a1, BiomekWell)
+ self.assertEqual(a1.segments, ()) # a V bottom Biomek does not outline
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pylabrobot/resources/beckman_coulter/biomek_resource.py b/pylabrobot/resources/beckman_coulter/biomek_resource.py
new file mode 100644
index 00000000000..63f6721c23d
--- /dev/null
+++ b/pylabrobot/resources/beckman_coulter/biomek_resource.py
@@ -0,0 +1,219 @@
+"""Biomek's own shapes on PyLabRobot's resources: a tip's cone and a well's outline by height.
+
+Biomek describes a tip by its length, capacity and seating depth (which `Tip` holds) and also by its
+cone, and a well by its sections from the bottom up, each with an outline that changes with height.
+A Biomek touch-off places the tip against the wall at a height, so it needs both: these classes
+carry them, and everything else about the resource is PyLabRobot's.
+"""
+
+import math
+from dataclasses import asdict, dataclass
+from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union
+
+from pylabrobot.resources.coordinate import Coordinate
+from pylabrobot.resources.resource import Resource
+from pylabrobot.resources.tip import Tip
+from pylabrobot.resources.well import Well
+from pylabrobot.utils.interpolation import interpolate_1d
+
+
+class BiomekTip(Tip):
+ """A tip for Biomek instruments: a `Tip` with its cone, which Biomek uses to place the tip near a
+ wall (a touch-off), from `end_diameter` at its end to `diameter` over `cone_length` (mm)."""
+
+ def __init__(
+ self,
+ name: str,
+ diameter: float,
+ size_z: float,
+ has_filter: bool,
+ maximal_volume: float,
+ fitting_depth: float,
+ end_diameter: float,
+ cone_length: float,
+ nominal_volume: Optional[float] = None,
+ collar_height: Optional[float] = None,
+ category: str = "tip",
+ model: Optional[str] = None,
+ pick_up_location: Optional[Coordinate] = None,
+ is_conductive: Optional[bool] = None,
+ ):
+ """Initialize a Biomek tip with its dimensions and its cone."""
+ super().__init__(
+ name=name,
+ diameter=diameter,
+ size_z=size_z,
+ has_filter=has_filter,
+ maximal_volume=maximal_volume,
+ fitting_depth=fitting_depth,
+ nominal_volume=nominal_volume,
+ collar_height=collar_height,
+ category=category,
+ model=model,
+ pick_up_location=pick_up_location,
+ is_conductive=is_conductive,
+ )
+ self.end_diameter = end_diameter
+ self.cone_length = cone_length
+
+ def __eq__(self, other: object) -> bool:
+ """Compare tip fields and the cone."""
+ return (
+ isinstance(other, BiomekTip)
+ and super().__eq__(other)
+ and self.end_diameter == other.end_diameter
+ and self.cone_length == other.cone_length
+ )
+
+ def serialize(self) -> dict:
+ """Serialize a Biomek tip with its cone."""
+ return {
+ **super().serialize(),
+ "end_diameter": self.end_diameter,
+ "cone_length": self.cone_length,
+ }
+
+ def radius_at(self, from_end: float) -> float:
+ """The tip's outside radius `from_end` mm above its end: widening along the cone, then its
+ full radius."""
+ end, full = self.end_diameter / 2, self.get_size_x() / 2
+ if self.cone_length <= 0:
+ return full
+ return end + (full - end) * min(max(from_end, 0.0) / self.cone_length, 1.0)
+
+
+@dataclass(frozen=True)
+class WellSegment:
+ """One section of a Biomek well, from the bottom up, in mm.
+
+ Attributes:
+ height: how tall the section is.
+ top_x, top_y: its half-widths at its top (the radius, for a round section).
+ bottom_x, bottom_y: its half-widths at its bottom (0 for a cone from a point).
+ round: whether its outline is round (else a rectangle).
+ cap: a round bottom: a spherical cap reaching `top_x` at `height`.
+ """
+
+ height: float
+ top_x: float
+ top_y: float
+ bottom_x: float
+ bottom_y: float
+ round: bool = True
+ cap: bool = False
+
+ def half_widths(self, z: float) -> Tuple[float, float]:
+ """Half-widths (x, y), mm, `z` mm above the section's bottom."""
+ if self.cap:
+ sphere = (self.top_x * self.top_x + self.height * self.height) / (2 * self.height)
+ r = math.sqrt(max(0.0, 2 * sphere * z - z * z))
+ return r, r
+ t = z / self.height
+ return (
+ self.bottom_x + (self.top_x - self.bottom_x) * t,
+ self.bottom_y + (self.top_y - self.bottom_y) * t,
+ )
+
+ def area(self, z: float) -> float:
+ """Cross-section, mm^2, `z` mm above the section's bottom."""
+ hx, hy = self.half_widths(z)
+ return math.pi * hx * hy if self.round else 4 * hx * hy
+
+ def volume(self, h: float) -> float:
+ """uL (mm^3) in the bottom `h` mm of the section. The area is quadratic in z for every shape,
+ so Simpson's rule is exact."""
+ h = min(h, self.height)
+ if h <= 0:
+ return 0.0
+ return h / 6 * (self.area(0) + 4 * self.area(h / 2) + self.area(h))
+
+
+# mm between a height -> volume table's heights where a section's cross-section changes with height
+# (a cone, a cap): PyLabRobot interpolates between them.
+KNOT_STEP = 0.1
+
+
+class BiomekWell(Well):
+ """A well with Biomek's outline by height (`segments`, bottom up): its height <-> volume table
+ (`height_volume_data`) is made from them, and `wall_distance` says where its wall is at a height.
+ With no segments it is a plain `Well`."""
+
+ def __init__(
+ self,
+ name: str,
+ size_x: float,
+ size_y: float,
+ size_z: float,
+ segments: Sequence[Union[WellSegment, Mapping[str, Any]]] = (),
+ height_volume_data: Optional[Dict[float, float]] = None,
+ max_volume: Optional[float] = None,
+ **kwargs: Any,
+ ):
+ self.segments: Tuple[WellSegment, ...] = tuple(
+ s if isinstance(s, WellSegment) else WellSegment(**s) for s in segments
+ )
+ if height_volume_data is None and self.segments:
+ height_volume_data = self._height_volume_table(size_z)
+ if max_volume is None and height_volume_data is not None:
+ max_volume = interpolate_1d(size_z, height_volume_data, bounds_handling="error")
+ super().__init__(
+ name=name,
+ size_x=size_x,
+ size_y=size_y,
+ size_z=size_z,
+ height_volume_data=height_volume_data,
+ max_volume=max_volume,
+ **kwargs,
+ )
+
+ def half_widths(self, z: float) -> Tuple[float, float]:
+ """Half-widths (x, y), mm, `z` mm above the bottom (the top's above the top)."""
+ left = max(0.0, z)
+ for seg in self.segments:
+ if left <= seg.height:
+ return seg.half_widths(left)
+ left -= seg.height
+ last = self.segments[-1]
+ return last.half_widths(last.height)
+
+ def wall_distance(self, z: float, angle: float) -> float:
+ """How far, mm, the wall is from the well's axis `z` mm above its bottom, in direction `angle`
+ (radians): the radius for a round well, to the nearest side for a rectangular one."""
+ hx, hy = self.half_widths(z)
+ if all(s.round for s in self.segments):
+ return hx
+ c, s = abs(math.cos(angle)), abs(math.sin(angle))
+ return min(hx / c if c > 1e-12 else math.inf, hy / s if s > 1e-12 else math.inf)
+
+ def volume_at(self, z: float) -> float:
+ """uL held `z` mm above the bottom, by the segments."""
+ left, v = z, 0.0
+ for seg in self.segments:
+ v += seg.volume(left)
+ left -= seg.height
+ if left <= 0:
+ break
+ return v
+
+ def _height_volume_table(self, depth: float) -> Dict[float, float]:
+ """A point at each section's ends, and every `KNOT_STEP` in a section whose cross-section
+ changes, up to the rim."""
+ zs = [0.0]
+ for seg in self.segments:
+ h = seg.height
+ constant = seg.half_widths(0.0) == seg.half_widths(h) == seg.half_widths(h / 2)
+ n = 1 if constant else max(1, math.ceil(h / KNOT_STEP))
+ zs += [zs[-1] + h * i / n for i in range(1, n + 1)]
+ if depth > zs[-1]:
+ zs.append(depth)
+ return {round(z, 6): self.volume_at(z) for z in zs}
+
+ def __eq__(self, other: object) -> bool:
+ return (
+ isinstance(other, BiomekWell) and super().__eq__(other) and self.segments == other.segments
+ )
+
+ __hash__ = Resource.__hash__
+
+ def serialize(self) -> dict:
+ return {**super().serialize(), "segments": [asdict(s) for s in self.segments]}
diff --git a/pylabrobot/resources/beckman_coulter/plates.py b/pylabrobot/resources/beckman_coulter/plates.py
new file mode 100644
index 00000000000..62de4335952
--- /dev/null
+++ b/pylabrobot/resources/beckman_coulter/plates.py
@@ -0,0 +1,348 @@
+"""Plates and reservoirs on Biomek's labware classes (cm there, mm here).
+
+- `xspan`, `yspan`, `height`: the footprint and height; `wellsx` / `wellsy`, `wellxspacing` /
+ `wellyspacing`, `well1xoffset` / `well1yoffset` (A1's centre from the left and back edges): the
+ grid; `welldepth`, the top segment's `topx` / `topy`: a well's size.
+- `segments`: a well's outline from the bottom up (`WellSegment`), which gives its height <->
+ volume table and where its wall is.
+- a reservoir's `sections`: its wells, `x1..x2`, `y1..y2` from the left and back edges, `depth`.
+- `gripperinfo`: where Biomek's gripper pads go (`preferred_pickup_location`), the fingertips
+ `gripperzoffset` above the bottom (below it for a plate).
+- `stackablelabwareclasses`: how deep a lid sits on it.
+"""
+
+from typing import Dict, Optional
+
+from pylabrobot.resources.coordinate import Coordinate
+from pylabrobot.resources.lid import Lid
+from pylabrobot.resources.plate import Plate
+from pylabrobot.resources.utils import create_ordered_items_2d
+from pylabrobot.resources.well import CrossSectionType, Well, WellBottomType
+
+from .biomek_resource import BiomekWell, WellSegment
+
+_96_WELLPLATE_VB_SEGMENTS = (
+ WellSegment(2.0, 2.735, 2.735, 0.0, 0.0),
+ WellSegment(8.5, 4.0, 4.0, 4.0, 4.0),
+)
+
+_96_WELLPLATE_FLAT_SEGMENTS = (WellSegment(10.668, 3.43, 3.43, 3.175, 3.175),)
+
+_96_DEEPWELL_SQUARE_SEGMENTS = (
+ WellSegment(8.61, 3.85, 3.85, 0.0, 0.0),
+ WellSegment(33.3, 4.14, 4.14, 4.14, 4.14, round=False),
+)
+
+_24_WELLPLATE_SQUARE_RB_SEGMENTS = (
+ WellSegment(8.0, 8.0, 8.0, 0.0, 0.0, cap=True),
+ WellSegment(32.0, 8.5, 8.5, 8.5, 8.5, round=False),
+)
+
+
+def beckman_coulter_biomek_96_wellplate_vb(name: str, with_lid: bool = False) -> Plate:
+ """Greiner polystyrene microplate with 96 round, V-bottomed wells. Part no. 651XXX.
+
+ Biomek labware class Thermo96VB_PP."""
+ lid: Optional[Lid] = None
+ if with_lid:
+ # PyLabRobot's lid covers the plate's footprint; Biomek seats it
+ # (stackablelabwareclasses TiterplateLid: x 0.04, y 0.152, z 0.8 cm) 6.1 mm into the plate.
+ lid = Lid(
+ name=f"{name}_lid",
+ size_x=127.8,
+ size_y=85.6,
+ size_z=10.0, # TiterplateLid height 1.0 cm
+ nesting_z_height=6.1,
+ model="beckman_coulter_biomek_lid_titerplatelid",
+ )
+ # Biomek's pads: the TiterplateLid's own centre on its seat, gripperzoffset above its bottom.
+ lid.preferred_pickup_location = Coordinate(63.9, 42.805, 2.0)
+ plate = Plate(
+ name=name,
+ size_x=127.8, # xspan 12.78 cm
+ size_y=85.6, # yspan 8.56 cm
+ size_z=14.1, # height 1.41 cm
+ model=beckman_coulter_biomek_96_wellplate_vb.__name__,
+ lid=lid,
+ ordered_items=create_ordered_items_2d(
+ BiomekWell,
+ num_items_x=12,
+ num_items_y=8,
+ dx=11.31, # well1xoffset 1.44 cm, less half the well
+ dy=8.31, # the front row; A1 (well1yoffset 1.12 cm) is at the back
+ dz=3.6,
+ item_dx=9.0,
+ item_dy=9.0,
+ size_x=6.18,
+ size_y=6.18,
+ size_z=10.5, # welldepth 1.05 cm
+ bottom_type=WellBottomType.V,
+ cross_section_type=CrossSectionType.CIRCLE,
+ segments=_96_WELLPLATE_VB_SEGMENTS,
+ max_volume=440.0, # wellvolume
+ name_prefix=name,
+ ),
+ )
+ plate.preferred_pickup_location = Coordinate(63.9, 42.8, -2.3)
+ return plate
+
+
+def beckman_coulter_biomek_96_wellplate_flat(name: str, with_lid: bool = False) -> Plate:
+ """Beckman Coulter microplate with 96 round, flat-bottomed wells. Part no. 609844.
+
+ Biomek labware class BCFlat96."""
+ lid: Optional[Lid] = None
+ if with_lid:
+ # PyLabRobot's lid covers the plate's footprint; Biomek seats it
+ # (stackablelabwareclasses TiterplateLid: x 0.038, y 0.146, z 0.8 cm) 6.224 mm into the plate.
+ lid = Lid(
+ name=f"{name}_lid",
+ size_x=127.762,
+ size_y=85.471,
+ size_z=10.0, # TiterplateLid height 1.0 cm
+ nesting_z_height=6.224,
+ model="beckman_coulter_biomek_lid_titerplatelid",
+ )
+ # Biomek's pads: the TiterplateLid's own centre on its seat, gripperzoffset above its bottom.
+ lid.preferred_pickup_location = Coordinate(63.88, 42.736, 2.0)
+ plate = Plate(
+ name=name,
+ size_x=127.762, # xspan 12.7762 cm
+ size_y=85.471, # yspan 8.5471 cm
+ size_z=14.224, # height 1.4224 cm
+ model=beckman_coulter_biomek_96_wellplate_flat.__name__,
+ lid=lid,
+ ordered_items=create_ordered_items_2d(
+ BiomekWell,
+ num_items_x=12,
+ num_items_y=8,
+ dx=10.95, # well1xoffset 1.438 cm, less half the well
+ dy=7.811, # the front row; A1 (well1yoffset 1.123 cm) is at the back
+ dz=3.556,
+ item_dx=9.0,
+ item_dy=9.0,
+ size_x=6.86,
+ size_y=6.86,
+ size_z=10.668, # welldepth 1.0668 cm
+ bottom_type=WellBottomType.FLAT,
+ cross_section_type=CrossSectionType.CIRCLE,
+ segments=_96_WELLPLATE_FLAT_SEGMENTS,
+ max_volume=362.76, # wellvolume
+ name_prefix=name,
+ ),
+ )
+ plate.preferred_pickup_location = Coordinate(63.881, 42.7355, -2.3)
+ return plate
+
+
+def beckman_coulter_biomek_96_deepwell_square(name: str) -> Plate:
+ """Beckman Coulter microplate with 96 deep, square, V-bottomed wells. Part no. 140504.
+
+ Biomek labware class BCDeep96Square."""
+ plate = Plate(
+ name=name,
+ size_x=128.17, # xspan 12.817 cm
+ size_y=85.98, # yspan 8.598 cm
+ size_z=44.2, # height 4.42 cm
+ model=beckman_coulter_biomek_96_deepwell_square.__name__,
+ ordered_items=create_ordered_items_2d(
+ BiomekWell,
+ num_items_x=12,
+ num_items_y=8,
+ dx=10.2364, # well1xoffset 1.43764 cm, less half the well
+ dy=7.46, # the front row; A1 (well1yoffset 1.138 cm) is at the back
+ dz=2.29,
+ item_dx=9.0,
+ item_dy=9.0,
+ size_x=8.28,
+ size_y=8.28,
+ size_z=41.91, # welldepth 4.191 cm
+ bottom_type=WellBottomType.V,
+ cross_section_type=CrossSectionType.RECTANGLE,
+ segments=_96_DEEPWELL_SQUARE_SEGMENTS,
+ max_volume=2200.0, # wellvolume
+ name_prefix=name,
+ ),
+ )
+ plate.preferred_pickup_location = Coordinate(64.085, 42.99, -2.3)
+ return plate
+
+
+def beckman_coulter_biomek_24_wellplate_square_rb(name: str, with_lid: bool = False) -> Plate:
+ """Thomson microplate with 24 square, round-bottomed wells. Part no. 931568.
+
+ Biomek labware class Thomson_24w_Square_RB."""
+ lid: Optional[Lid] = None
+ if with_lid:
+ # PyLabRobot's lid covers the plate's footprint; Biomek seats it
+ # (stackablelabwareclasses Thomson_24w_Square_RB_Lid: x 0.0, y 0.0, z 3.4 cm) 10.0 mm into the plate.
+ lid = Lid(
+ name=f"{name}_lid",
+ size_x=127.762,
+ size_y=85.471,
+ size_z=10.0, # Thomson_24w_Square_RB_Lid height 1.0 cm
+ nesting_z_height=10.0,
+ model="beckman_coulter_biomek_lid_thomson_24w_square_rb_lid",
+ )
+ # Biomek's pads: the Thomson_24w_Square_RB_Lid's own centre on its seat, gripperzoffset above its bottom.
+ lid.preferred_pickup_location = Coordinate(63.5, 44.196, 8.0)
+ plate = Plate(
+ name=name,
+ size_x=127.762, # xspan 12.7762 cm
+ size_y=85.471, # yspan 8.5471 cm
+ size_z=44.0, # height 4.4 cm
+ model=beckman_coulter_biomek_24_wellplate_square_rb.__name__,
+ lid=lid,
+ ordered_items=create_ordered_items_2d(
+ BiomekWell,
+ num_items_x=6,
+ num_items_y=4,
+ dx=10.5, # well1xoffset 1.9 cm, less half the well
+ dy=6.971, # the front row; A1 (well1yoffset 1.6 cm) is at the back
+ dz=4.0,
+ item_dx=18.0,
+ item_dy=18.0,
+ size_x=17.0,
+ size_y=17.0,
+ size_z=40.0, # welldepth 4.0 cm
+ bottom_type=WellBottomType.U,
+ cross_section_type=CrossSectionType.RECTANGLE,
+ segments=_24_WELLPLATE_SQUARE_RB_SEGMENTS,
+ max_volume=10000.0, # wellvolume
+ name_prefix=name,
+ ),
+ )
+ plate.preferred_pickup_location = Coordinate(63.881, 42.7355, -2.3)
+ return plate
+
+
+def beckman_coulter_biomek_reservoir_350cb(name: str, with_lid: bool = False) -> Plate:
+ """Thermo Nunc reservoir with one flat-bottomed section.
+
+ Biomek labware class ThermoNUNC_350CB: a well per section."""
+ lid: Optional[Lid] = None
+ if with_lid:
+ # PyLabRobot's lid covers the plate's footprint; Biomek seats it
+ # (stackablelabwareclasses TiterplateLid: x 0.0, y 0.0, z 3.4 cm) 4.0 mm into the plate.
+ lid = Lid(
+ name=f"{name}_lid",
+ size_x=127.8,
+ size_y=85.85,
+ size_z=10.0, # TiterplateLid height 1.0 cm
+ nesting_z_height=4.0,
+ model="beckman_coulter_biomek_lid_titerplatelid",
+ )
+ # Biomek's pads: the TiterplateLid's own centre on its seat, gripperzoffset above its bottom.
+ lid.preferred_pickup_location = Coordinate(63.5, 44.575, 2.0)
+ wells: Dict[str, Well] = {}
+ wells["A1"] = BiomekWell(
+ name=f"{name}_A1",
+ size_x=123.8, # x1 0.2 to x2 12.58 cm
+ size_y=81.5, # y1 0.2 to y2 8.35 cm
+ size_z=37.4, # depth 3.74 cm
+ segments=(WellSegment(37.4, 61.9, 40.75, 61.9, 40.75, round=False),),
+ bottom_type=WellBottomType.FLAT,
+ cross_section_type=CrossSectionType.RECTANGLE,
+ max_volume=300000.0, # maxvolume
+ )
+ wells["A1"].location = Coordinate(2.0, 2.35, 0.6)
+ plate = Plate(
+ name=name,
+ size_x=127.8, # xspan 12.78 cm
+ size_y=85.85, # yspan 8.585 cm
+ size_z=38.0, # height 3.8 cm
+ model=beckman_coulter_biomek_reservoir_350cb.__name__,
+ lid=lid,
+ ordered_items=wells,
+ )
+ plate.preferred_pickup_location = Coordinate(63.9, 42.925, -2.0)
+ return plate
+
+
+def beckman_coulter_biomek_reservoir(name: str) -> Plate:
+ """Reservoir used with the Multimek. Part no. 148033.
+
+ Biomek labware class Reservoir: a well per section."""
+ wells: Dict[str, Well] = {}
+ wells["A1"] = BiomekWell(
+ name=f"{name}_A1",
+ size_x=111.04, # x1 0.826 to x2 11.93 cm
+ size_y=72.65, # y1 0.635 to y2 7.9 cm
+ size_z=14.53, # depth 1.453 cm
+ segments=(WellSegment(14.53, 55.52, 36.325, 55.52, 36.325, round=False),),
+ bottom_type=WellBottomType.FLAT,
+ cross_section_type=CrossSectionType.RECTANGLE,
+ max_volume=110000.0, # maxvolume
+ )
+ wells["A1"].location = Coordinate(8.26, 3.55, 14.68)
+ plate = Plate(
+ name=name,
+ size_x=127.0, # xspan 12.7 cm
+ size_y=82.55, # yspan 8.255 cm
+ size_z=29.21, # height 2.921 cm
+ model=beckman_coulter_biomek_reservoir.__name__,
+ ordered_items=wells,
+ )
+ plate.preferred_pickup_location = Coordinate(63.5, 41.275, -2.3)
+ return plate
+
+
+def beckman_coulter_biomek_modular_reservoir(name: str) -> Plate:
+ """Beckman Coulter reservoir that may be customized with added sections. Part no. 372795 (Frame); 372790(Quarter); 373792(Quarter Divided by Width); 372788 (Quarter Divided by Length); 372786(Half); 372794(Half Divided by Width).
+
+ Biomek labware class ModularReservoir: a well per section."""
+ wells: Dict[str, Well] = {}
+ wells["A1"] = BiomekWell(
+ name=f"{name}_A1",
+ size_x=23.65, # x1 1.105 to x2 3.47 cm
+ size_y=69.19, # y1 0.772 to y2 7.691 cm
+ size_z=24.79, # depth 2.479 cm
+ # a V bottom 1.156 cm deep: no outline
+ bottom_type=WellBottomType.V,
+ cross_section_type=CrossSectionType.RECTANGLE,
+ max_volume=40700.0, # maxvolume
+ )
+ wells["A1"].location = Coordinate(11.05, 8.69, 14.07)
+ wells["A2"] = BiomekWell(
+ name=f"{name}_A2",
+ size_x=23.65, # x1 3.84825 to x2 6.21325 cm
+ size_y=69.19, # y1 0.772 to y2 7.691 cm
+ size_z=24.79, # depth 2.479 cm
+ # a V bottom 1.156 cm deep: no outline
+ bottom_type=WellBottomType.V,
+ cross_section_type=CrossSectionType.RECTANGLE,
+ max_volume=40700.0, # maxvolume
+ )
+ wells["A2"].location = Coordinate(38.4825, 8.69, 14.07)
+ wells["A3"] = BiomekWell(
+ name=f"{name}_A3",
+ size_x=23.65, # x1 6.5915 to x2 8.9565 cm
+ size_y=69.19, # y1 0.772 to y2 7.691 cm
+ size_z=24.79, # depth 2.479 cm
+ # a V bottom 1.156 cm deep: no outline
+ bottom_type=WellBottomType.V,
+ cross_section_type=CrossSectionType.RECTANGLE,
+ max_volume=40700.0, # maxvolume
+ )
+ wells["A3"].location = Coordinate(65.915, 8.69, 14.07)
+ wells["A4"] = BiomekWell(
+ name=f"{name}_A4",
+ size_x=23.65, # x1 9.33475 to x2 11.69975 cm
+ size_y=69.19, # y1 0.772 to y2 7.691 cm
+ size_z=24.79, # depth 2.479 cm
+ # a V bottom 1.156 cm deep: no outline
+ bottom_type=WellBottomType.V,
+ cross_section_type=CrossSectionType.RECTANGLE,
+ max_volume=40700.0, # maxvolume
+ )
+ wells["A4"].location = Coordinate(93.3475, 8.69, 14.07)
+ plate = Plate(
+ name=name,
+ size_x=127.41, # xspan 12.741 cm
+ size_y=85.6, # yspan 8.56 cm
+ size_z=38.86, # height 3.886 cm
+ model=beckman_coulter_biomek_modular_reservoir.__name__,
+ ordered_items=wells,
+ )
+ plate.preferred_pickup_location = Coordinate(63.705, 42.8, -2.3)
+ return plate
diff --git a/pylabrobot/resources/beckman_coulter/tip_racks.py b/pylabrobot/resources/beckman_coulter/tip_racks.py
new file mode 100644
index 00000000000..1e8ef072f54
--- /dev/null
+++ b/pylabrobot/resources/beckman_coulter/tip_racks.py
@@ -0,0 +1,179 @@
+"""Beckman Coulter Biomek tip boxes, from Biomek's labware classes (cm there, mm here).
+
+- `xspan`, `yspan`, `height`: the box's footprint and height, tips in.
+- `wellsx`, `wellsy`, `wellxspacing`, `wellyspacing`: the tip grid.
+- `well1xoffset`, `well1yoffset`: tip A1's centre, from the box's left and back edges.
+- `wellradius`: the radius of the hole a tip stands in.
+- `gripperinfo`: where Biomek's gripper pads go (`preferred_pickup_location`).
+
+The tips' tops are at the box's `height`, where the head's mandrels meet them, so a tip spot sits
+on the top face, as on a nested rack.
+"""
+
+from pylabrobot.resources.coordinate import Coordinate
+from pylabrobot.resources.tip_rack import StandingTipRack, TipSpot
+from pylabrobot.resources.utils import create_ordered_items_2d
+
+from .tips import (
+ beckman_coulter_biomek_tip_50uL_filter,
+ beckman_coulter_biomek_tip_190uL_filter,
+ beckman_coulter_biomek_tip_230uL,
+ beckman_coulter_biomek_tip_1025uL_filter,
+ beckman_coulter_biomek_tip_1070uL,
+)
+
+
+def beckman_coulter_biomek_96_tiprack_50uL_filter(
+ name: str, with_tips: bool = True
+) -> StandingTipRack:
+ """Biomek BC50F tip box: 96 T50F tips (`beckman_coulter_biomek_tip_50uL_filter`). Beckman Coulter tip box containing 96 Aerosol Resistant T50 filter tips. Part no. B85888.
+
+ Labware class BC50F."""
+ rack = StandingTipRack(
+ name=name,
+ size_x=127.9, # xspan 12.79 cm
+ size_y=85.4, # yspan 8.54 cm
+ size_z=55.9, # height 5.59 cm
+ model=beckman_coulter_biomek_96_tiprack_50uL_filter.__name__,
+ ordered_items=create_ordered_items_2d(
+ TipSpot,
+ num_items_x=12,
+ num_items_y=8,
+ dx=11.7, # well1xoffset 1.45 cm, less the hole's radius
+ dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back
+ dz=55.9,
+ item_dx=9.0,
+ item_dy=9.0,
+ size_x=5.6, # wellradius 0.28 cm
+ size_y=5.6,
+ make_tip=beckman_coulter_biomek_tip_50uL_filter,
+ name_prefix=name,
+ ),
+ with_tips=with_tips,
+ )
+ rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3)
+ return rack
+
+
+def beckman_coulter_biomek_96_tiprack_190uL_filter(
+ name: str, with_tips: bool = True
+) -> StandingTipRack:
+ """Biomek BC190F tip box: 96 T190F tips (`beckman_coulter_biomek_tip_190uL_filter`). Beckman Coulter tip box containing 96 Aerosol Resistant T190 filter tips. Part no. B85911.
+
+ Labware class BC190F."""
+ rack = StandingTipRack(
+ name=name,
+ size_x=127.9, # xspan 12.79 cm
+ size_y=85.4, # yspan 8.54 cm
+ size_z=55.9, # height 5.59 cm
+ model=beckman_coulter_biomek_96_tiprack_190uL_filter.__name__,
+ ordered_items=create_ordered_items_2d(
+ TipSpot,
+ num_items_x=12,
+ num_items_y=8,
+ dx=11.7, # well1xoffset 1.45 cm, less the hole's radius
+ dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back
+ dz=55.9,
+ item_dx=9.0,
+ item_dy=9.0,
+ size_x=5.6, # wellradius 0.28 cm
+ size_y=5.6,
+ make_tip=beckman_coulter_biomek_tip_190uL_filter,
+ name_prefix=name,
+ ),
+ with_tips=with_tips,
+ )
+ rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3)
+ return rack
+
+
+def beckman_coulter_biomek_96_tiprack_230uL(name: str, with_tips: bool = True) -> StandingTipRack:
+ """Biomek BC230 tip box: 96 T230 tips (`beckman_coulter_biomek_tip_230uL`). Beckman Coulter tip box containing 96 T230 tips. Part no. Sterile: B85906, Non-Sterile: B85903.
+
+ Labware class BC230."""
+ rack = StandingTipRack(
+ name=name,
+ size_x=127.9, # xspan 12.79 cm
+ size_y=85.4, # yspan 8.54 cm
+ size_z=55.9, # height 5.59 cm
+ model=beckman_coulter_biomek_96_tiprack_230uL.__name__,
+ ordered_items=create_ordered_items_2d(
+ TipSpot,
+ num_items_x=12,
+ num_items_y=8,
+ dx=11.7, # well1xoffset 1.45 cm, less the hole's radius
+ dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back
+ dz=55.9,
+ item_dx=9.0,
+ item_dy=9.0,
+ size_x=5.6, # wellradius 0.28 cm
+ size_y=5.6,
+ make_tip=beckman_coulter_biomek_tip_230uL,
+ name_prefix=name,
+ ),
+ with_tips=with_tips,
+ )
+ rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3)
+ return rack
+
+
+def beckman_coulter_biomek_96_tiprack_1025uL_filter(
+ name: str, with_tips: bool = True
+) -> StandingTipRack:
+ """Biomek BC1025F tip box: 96 T1025F tips (`beckman_coulter_biomek_tip_1025uL_filter`). Beckman Coulter tip box containing 96 Aerosol Resistant T1025 filtered tips. Part no. B85955.
+
+ Labware class BC1025F."""
+ rack = StandingTipRack(
+ name=name,
+ size_x=127.9, # xspan 12.79 cm
+ size_y=85.4, # yspan 8.54 cm
+ size_z=114.1, # height 11.41 cm
+ model=beckman_coulter_biomek_96_tiprack_1025uL_filter.__name__,
+ ordered_items=create_ordered_items_2d(
+ TipSpot,
+ num_items_x=12,
+ num_items_y=8,
+ dx=11.6, # well1xoffset 1.44 cm, less the hole's radius
+ dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back
+ dz=114.1,
+ item_dx=9.0,
+ item_dy=9.0,
+ size_x=5.6, # wellradius 0.28 cm
+ size_y=5.6,
+ make_tip=beckman_coulter_biomek_tip_1025uL_filter,
+ name_prefix=name,
+ ),
+ with_tips=with_tips,
+ )
+ rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3)
+ return rack
+
+
+def beckman_coulter_biomek_96_tiprack_1070uL(name: str, with_tips: bool = True) -> StandingTipRack:
+ """Biomek BC1070 tip box: 96 T1070 tips (`beckman_coulter_biomek_tip_1070uL`). Beckman Coulter tip box containing 96 T1070 tips. Part no. Sterile: B85945, Non-Sterile: B85940.
+
+ Labware class BC1070."""
+ rack = StandingTipRack(
+ name=name,
+ size_x=127.9, # xspan 12.79 cm
+ size_y=85.4, # yspan 8.54 cm
+ size_z=114.1, # height 11.41 cm
+ model=beckman_coulter_biomek_96_tiprack_1070uL.__name__,
+ ordered_items=create_ordered_items_2d(
+ TipSpot,
+ num_items_x=12,
+ num_items_y=8,
+ dx=11.6, # well1xoffset 1.44 cm, less the hole's radius
+ dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back
+ dz=114.1,
+ item_dx=9.0,
+ item_dy=9.0,
+ size_x=5.6, # wellradius 0.28 cm
+ size_y=5.6,
+ make_tip=beckman_coulter_biomek_tip_1070uL,
+ name_prefix=name,
+ ),
+ with_tips=with_tips,
+ )
+ rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3)
+ return rack
diff --git a/pylabrobot/resources/beckman_coulter/tips.py b/pylabrobot/resources/beckman_coulter/tips.py
new file mode 100644
index 00000000000..756b870e92c
--- /dev/null
+++ b/pylabrobot/resources/beckman_coulter/tips.py
@@ -0,0 +1,96 @@
+"""Beckman Coulter Biomek tips, from Biomek's tip classes (lengths in cm there, mm here).
+
+- `tipheight`: the tip's length; `capacity`: its volume in uL; `filtered`: a filter tip.
+- `spanseatingdepth`: how far a mandrel goes into the tip.
+- `maxtipradius`: the tip's radius where it seats on the mandrel.
+- `mintipradius`, `coniclength`: its radius at the end, and the length over which it widens from
+ there to `maxtipradius` (the cone).
+- `lls`: whether the tip is conductive, for liquid-level sensing.
+"""
+
+from .biomek_resource import BiomekTip
+
+
+def beckman_coulter_biomek_tip_50uL_filter(name: str) -> BiomekTip:
+ """Biomek T50F tip, 50 uL, filter: tip class T50F."""
+ return BiomekTip(
+ name=name,
+ model=beckman_coulter_biomek_tip_50uL_filter.__name__,
+ diameter=5.182, # maxtipradius 0.2591 cm
+ size_z=51.359, # tipheight 5.1359 cm
+ has_filter=True,
+ maximal_volume=50.0, # capacity
+ nominal_volume=50.0,
+ fitting_depth=7.75, # spanseatingdepth 0.775 cm
+ end_diameter=0.812, # mintipradius 0.0406 cm
+ cone_length=38.227, # coniclength 3.8227 cm
+ is_conductive=False, # lls
+ )
+
+
+def beckman_coulter_biomek_tip_190uL_filter(name: str) -> BiomekTip:
+ """Biomek T190F tip, 190 uL, filter: tip class T190F."""
+ return BiomekTip(
+ name=name,
+ model=beckman_coulter_biomek_tip_190uL_filter.__name__,
+ diameter=4.826, # maxtipradius 0.2413 cm
+ size_z=51.435, # tipheight 5.1435 cm
+ has_filter=True,
+ maximal_volume=190.0, # capacity
+ nominal_volume=190.0,
+ fitting_depth=7.75, # spanseatingdepth 0.775 cm
+ end_diameter=1.27, # mintipradius 0.0635 cm
+ cone_length=28.194, # coniclength 2.8194 cm
+ is_conductive=False, # lls
+ )
+
+
+def beckman_coulter_biomek_tip_230uL(name: str) -> BiomekTip:
+ """Biomek T230 tip, 230 uL, no filter: tip class T230."""
+ return BiomekTip(
+ name=name,
+ model=beckman_coulter_biomek_tip_230uL.__name__,
+ diameter=4.826, # maxtipradius 0.2413 cm
+ size_z=51.435, # tipheight 5.1435 cm
+ has_filter=False,
+ maximal_volume=230.0, # capacity
+ nominal_volume=230.0,
+ fitting_depth=7.75, # spanseatingdepth 0.775 cm
+ end_diameter=1.27, # mintipradius 0.0635 cm
+ cone_length=28.194, # coniclength 2.8194 cm
+ is_conductive=False, # lls
+ )
+
+
+def beckman_coulter_biomek_tip_1025uL_filter(name: str) -> BiomekTip:
+ """Biomek T1025F tip, 1025 uL, filter: tip class T1025F."""
+ return BiomekTip(
+ name=name,
+ model=beckman_coulter_biomek_tip_1025uL_filter.__name__,
+ diameter=4.826, # maxtipradius 0.2413 cm
+ size_z=109.855, # tipheight 10.9855 cm
+ has_filter=True,
+ maximal_volume=1025.0, # capacity
+ nominal_volume=1025.0,
+ fitting_depth=7.75, # spanseatingdepth 0.775 cm
+ end_diameter=1.27, # mintipradius 0.0635 cm
+ cone_length=19.8374, # coniclength 1.98374 cm
+ is_conductive=False, # lls
+ )
+
+
+def beckman_coulter_biomek_tip_1070uL(name: str) -> BiomekTip:
+ """Biomek T1070 tip, 1070 uL, no filter: tip class T1070."""
+ return BiomekTip(
+ name=name,
+ model=beckman_coulter_biomek_tip_1070uL.__name__,
+ diameter=4.826, # maxtipradius 0.2413 cm
+ size_z=109.855, # tipheight 10.9855 cm
+ has_filter=False,
+ maximal_volume=1070.0, # capacity
+ nominal_volume=1070.0,
+ fitting_depth=7.75, # spanseatingdepth 0.775 cm
+ end_diameter=1.27, # mintipradius 0.0635 cm
+ cone_length=19.8374, # coniclength 1.98374 cm
+ is_conductive=False, # lls
+ )
diff --git a/pylabrobot/resources/n_channel_pipettes.py b/pylabrobot/resources/n_channel_pipettes.py
index 6e3fe04725c..72b6762fafe 100644
--- a/pylabrobot/resources/n_channel_pipettes.py
+++ b/pylabrobot/resources/n_channel_pipettes.py
@@ -4,7 +4,7 @@
from typing import Any, Dict, List, Literal, Mapping, Optional, cast, get_args
from pylabrobot.resources.coordinate import Coordinate
-from pylabrobot.resources.head_tool import HeadTool, move_tool
+from pylabrobot.resources.head_tool import HeadTool, move_tool, release_named_tool
from pylabrobot.resources.itemized_resource import ItemizedResource
from pylabrobot.resources.resource import Resource
from pylabrobot.resources.well import CrossSectionType
@@ -145,6 +145,31 @@ def tip_bottom(self) -> Optional[Coordinate]:
return None
return Coordinate(0.0, 0.0, cast(Coordinate, tip.location).z)
+ def serialize_state(self) -> Dict[str, Any]:
+ """This shaft's state: the tool it carries (`tip`, as it serializes; None for none), as a tip
+ spot's state holds its tip. A device that cannot sense its tips reads them back from it."""
+ tip = self.tip
+ return {**super().serialize_state(), "tip": None if tip is None else tip.serialize()}
+
+ def load_state(self, state: Dict[str, Any]) -> None:
+ """Load this shaft's state: the saved `tip` goes onto it (a tool of the same name held
+ elsewhere in the same tree gives way first); a saved None takes off the one it carries. State
+ saved before shafts had any leaves it as it is."""
+ super().load_state(state)
+ if "tip" not in state:
+ return
+ saved, current = state["tip"], self.tip
+ if current is not None and saved is not None and current.serialize() == saved:
+ return
+ if current is not None:
+ self.release_tip()
+ if saved is None:
+ return
+ release_named_tool(self.get_root(), saved["name"])
+ tip = Resource.deserialize(saved)
+ assert isinstance(tip, HeadTool)
+ self.mount_tip(tip)
+
def serialize(self) -> dict:
"""What its size does not say: how it holds a tip, and that it is round rather than a box."""
return {
diff --git a/pylabrobot/resources/n_channel_pipettes_tests.py b/pylabrobot/resources/n_channel_pipettes_tests.py
index 319a5211e0f..394256531d5 100644
--- a/pylabrobot/resources/n_channel_pipettes_tests.py
+++ b/pylabrobot/resources/n_channel_pipettes_tests.py
@@ -4,6 +4,7 @@
from pylabrobot.resources.hamilton import hamilton_core_gripper_tool, hamilton_tip_300uL
from pylabrobot.resources.n_channel_pipettes import TipMountingShaft
from pylabrobot.resources.resource import Resource
+from pylabrobot.resources.tip import Tip
class TestTipMountingShaft(unittest.TestCase):
@@ -18,6 +19,56 @@ def test_a_shaft_is_round(self):
TipMountingShaft(name="shaft", tip_pickup_mode="core", cross_section_type="rectangle")
+class ShaftSavesItsTip(unittest.TestCase):
+ """A shaft's state is the tool it carries, so a device that cannot sense its tips reads them back."""
+
+ def setUp(self):
+ self.shaft = TipMountingShaft(name="shaft", tip_pickup_mode="core")
+
+ def test_a_carried_tip_is_saved_and_read_back(self):
+ tip = hamilton_tip_300uL(name="tip")
+ self.shaft.mount_tip(tip)
+ tip.tracker.set_volume(120)
+ state = self.shaft.serialize_all_state()
+ self.assertEqual(state["shaft"]["tip"], tip.serialize())
+
+ other = TipMountingShaft(name="shaft", tip_pickup_mode="core")
+ other.load_all_state(state)
+ self.assertTrue(other.has_tip())
+ assert other.tip is not None
+ assert isinstance(other.tip, Tip)
+ self.assertEqual(other.tip.serialize(), tip.serialize())
+ self.assertEqual(other.tip.location, tip.location)
+ self.assertEqual(other.tip.tracker.get_used_volume(), 120) # the tip's own state, after it
+
+ def test_none_saved_takes_the_tip_off(self):
+ empty = self.shaft.serialize_all_state()
+ self.assertIsNone(empty["shaft"]["tip"])
+ self.shaft.mount_tip(hamilton_tip_300uL(name="tip"))
+ self.shaft.load_all_state(empty)
+ self.assertFalse(self.shaft.has_tip())
+
+ def test_the_same_tip_stays_and_older_state_leaves_it(self):
+ tip = hamilton_tip_300uL(name="tip")
+ self.shaft.mount_tip(tip)
+ self.shaft.load_state(self.shaft.serialize_state())
+ self.assertIs(self.shaft.tip, tip)
+ self.shaft.load_state({})
+ self.assertIs(self.shaft.tip, tip)
+
+ def test_a_tip_of_that_name_held_elsewhere_gives_way(self):
+ root = Resource("root", size_x=100, size_y=100, size_z=10)
+ first = TipMountingShaft(name="first", tip_pickup_mode="core")
+ second = TipMountingShaft(name="second", tip_pickup_mode="core")
+ root.assign_child_resource(first, location=Coordinate.zero())
+ root.assign_child_resource(second, location=Coordinate(20, 0, 0))
+ first.mount_tip(hamilton_tip_300uL(name="tip"))
+ saved = first.serialize_state()
+ second.load_state(saved)
+ self.assertTrue(second.has_tip())
+ self.assertFalse(first.has_tip())
+
+
class ShaftHoldsItsTip(unittest.TestCase):
"""A mounting shaft carries its tip as a child, gripping it by the fitting depth."""