Skip to content

session

session

Gantry commissioning and motion session — position recording and jogging.

This module is backend-agnostic. It does not depend on prompt_toolkit or rich and can be imported and tested without the teach extra installed, as long as applied_motion.cli (the package guard) is not triggered first.

The MotionSession class deliberately avoids calling any private attributes of Gantry. PLC-specific actions (TEACH_POS, TEACH_TRAY) are delegated to the caller via the on_capture hook, keeping this class backend-agnostic and independently unit-testable.

OnCaptureHook module-attribute

OnCaptureHook = Callable[[str, dict[str, float]], None]

Type alias for the optional capture hook.

Signature: on_capture(label: str, position: dict[str, float]) -> None

Called after every successful MotionSession.capture with the position label and the recorded position dict. Typical uses:

  • Send TEACH_POS / TEACH_TRAY to the CECC-X PLC via FPosBAPIClient.
  • Emit an event to a higher-level orchestration layer.
  • Write a running log to a remote database.

MotionSession

MotionSession(
    gantry: Gantry, on_capture: OnCaptureHook | None = None
)

Records gantry positions interactively or programmatically.

Provides step-jog and position capture on top of a connected Gantry. Captured positions are kept in positions and can be persisted to and from JSON via save / load.

This class has no knowledge of the gantry backend (Modbus vs FPosBAPI) and no dependency on prompt_toolkit or rich. Backend-specific post-capture actions (e.g. sending TEACH_POS to the PLC) are performed by the caller through the on_capture hook.

Parameters:

Name Type Description Default
gantry Gantry

Connected and homed Gantry instance.

required
on_capture OnCaptureHook | None

Optional hook called immediately after each successful capture. Receives the position label and position dict. Exceptions raised by the hook propagate to the caller.

None

Attributes:

Name Type Description
positions dict[str, dict[str, float]]

Ordered dict mapping label → {axis_name: position_mm}. Populated by capture and load.

Example::

1
2
3
4
5
6
7
8
9
# FPosBAPI: wire a hook that commits positions to the PLC
def plc_hook(label, pos):
    gantry.teach_pos(pos_id=label_to_id[label])


session = MotionSession(gantry, on_capture=plc_hook)
session.jog("X", "+", 5.0)
session.capture("deck_a1")
session.save("deck_layout.json")
Source code in src/applied_motion/cli/session.py
def __init__(  # noqa
    self,
    gantry: Gantry,
    on_capture: OnCaptureHook | None = None,
) -> None:
    self.gantry = gantry
    self.on_capture = on_capture
    self.positions: dict[str, dict[str, float]] = {}
    logger.debug(
        "MotionSession: created for gantry=%r hook=%s",
        gantry,
        getattr(on_capture, "__name__", repr(on_capture)) if on_capture is not None else "None",
    )

jog

jog(
    axis_name: str,
    direction: str,
    step_mm: float,
    velocity: float = 10.0,
    timeout: int = 15,
) -> dict[str, float]

Step-move one axis by step_mm in direction.

Reads the current axis position, computes an absolute target, and dispatches a single-axis move via Gantry.move_to.

Parameters:

Name Type Description Default
axis_name str

Name of the axis to jog (must be a key in axes).

required
direction str

"+" to move in the positive direction, "-" to move in the negative direction.

required
step_mm float

Distance to step in millimetres. Must be positive.

required
velocity float

Jog speed in mm/s. Defaults to 10.0.

10.0
timeout int

Maximum seconds to wait for the move to complete. When exceeded the axis backend issues a stop command and the move is abandoned. Defaults to 30 seconds — long enough for any normal jog step, but ensures the axis will always halt rather than run indefinitely.

15

Returns:

Type Description
dict[str, float]

Full gantry location dict after the move completes.

Raises:

Type Description
ValueError

If direction is not "+" or "-", or if step_mm is not positive.

KeyError

If axis_name is not registered with the gantry.

Source code in src/applied_motion/cli/session.py
def jog(
    self,
    axis_name: str,
    direction: str,
    step_mm: float,
    velocity: float = 10.0,
    timeout: int = 15,
) -> dict[str, float]:
    """Step-move one axis by *step_mm* in *direction*.

    Reads the current axis position, computes an absolute target, and
    dispatches a single-axis move via
    [`Gantry.move_to`][applied_motion.applied_motion.Gantry.move_to].

    Args:
        axis_name: Name of the axis to jog (must be a key in
            ``axes``).
        direction: ``"+"`` to move in the positive direction, ``"-"``
            to move in the negative direction.
        step_mm: Distance to step in millimetres.  Must be positive.
        velocity: Jog speed in mm/s.  Defaults to ``10.0``.
        timeout: Maximum seconds to wait for the move to complete.
            When exceeded the axis backend issues a stop command and
            the move is abandoned.  Defaults to ``30`` seconds —
            long enough for any normal jog step, but ensures the
            axis will always halt rather than run indefinitely.

    Returns:
        Full gantry location dict after the move completes.

    Raises:
        ValueError: If *direction* is not ``"+"`` or ``"-"``, or if
            *step_mm* is not positive.
        KeyError: If *axis_name* is not registered with the gantry.
    """
    if direction not in ("+", "-"):
        raise ValueError(f"direction must be '+' or '-', got {direction!r}")
    if step_mm <= 0:
        raise ValueError(f"step_mm must be positive, got {step_mm!r}")
    if axis_name not in self.gantry.axes:
        raise KeyError(f"Axis {axis_name!r} is not registered with this gantry")

    axis = self.gantry.axes[axis_name]
    current = axis.get_current_axis_position()
    raw_delta = step_mm if direction == "+" else -step_mm
    if raw_delta > 0:
        available = max(0.0, axis.max_position - current - _JOG_LIMIT_MARGIN)
        delta = min(raw_delta, available)
    else:
        available = max(0.0, current - axis.min_position - _JOG_LIMIT_MARGIN)
        delta = max(raw_delta, -available)

    logger.info(
        "MotionSession.jog: axis=%s limits=[%.3f, %.3f] mm current=%.3f delta=%.3f vel=%.1f mm/s timeout=%ss",
        axis_name,
        axis.min_position,
        axis.max_position,
        current,
        delta,
        velocity,
        timeout,
    )
    if delta != raw_delta:
        logger.warning(
            "MotionSession.jog: axis=%s delta clamped %.3f\u2192%.3f mm (%s mm margin from SW limit)",
            axis_name,
            raw_delta,
            delta,
            _JOG_LIMIT_MARGIN,
        )
    if abs(delta) < 1e-3:
        logger.info("MotionSession.jog: axis=%s at limit, skipping move", axis_name)
        return self.gantry.get_location()

    axis.move(delta, velocity, position_type="relative", timeout=timeout)
    location = self.gantry.get_location()
    logger.debug("MotionSession.jog: post-move location=%s", location)
    return location

capture

capture(label: str) -> dict[str, float]

Record the current gantry position under label.

Calls Gantry.get_location, stores the result in positions, then invokes on_capture if one was provided.

Parameters:

Name Type Description Default
label str

Unique name for this position (e.g. "deck_a1"). Overwrites any previous entry with the same label.

required

Returns:

Type Description
dict[str, float]

The recorded position dict {axis_name: position_mm}.

Source code in src/applied_motion/cli/session.py
def capture(self, label: str) -> dict[str, float]:
    """Record the current gantry position under *label*.

    Calls [`Gantry.get_location`][applied_motion.applied_motion.Gantry.get_location], stores
    the result in ``positions``, then invokes *on_capture* if one
    was provided.

    Args:
        label: Unique name for this position (e.g. ``"deck_a1"``).
            Overwrites any previous entry with the same label.

    Returns:
        The recorded position dict ``{axis_name: position_mm}``.

    Raises:
        Any exception raised by *on_capture* propagates unchanged.
    """
    position = self.gantry.get_location()
    self.positions[label] = position
    logger.info("MotionSession.capture: label=%r position=%s", label, position)
    if self.on_capture is not None:
        self.on_capture(label, position)
    return position

save

save(path: Path | str) -> None

Write all captured positions to a JSON file.

The output format is a plain JSON object mapping label → {axis_name: position_mm}.

Parameters:

Name Type Description Default
path Path | str

Destination file path. Parent directories must exist.

required
Source code in src/applied_motion/cli/session.py
def save(self, path: Path | str) -> None:
    """Write all captured positions to a JSON file.

    The output format is a plain JSON object mapping label →
    ``{axis_name: position_mm}``.

    Args:
        path: Destination file path.  Parent directories must exist.
    """
    path = Path(path)
    with path.open("w") as fh:
        json.dump(self.positions, fh, indent=2)
    logger.info("MotionSession.save: wrote %d position(s) to %s", len(self.positions), path)

load

load(path: Path | str) -> None

Merge positions from a JSON file into positions.

Existing labels are overwritten by entries from path; labels absent in path are preserved.

Parameters:

Name Type Description Default
path Path | str

Source JSON file previously written by save.

required

Raises:

Type Description
OSError

If path cannot be opened.

ValueError

If the file contains invalid JSON.

Source code in src/applied_motion/cli/session.py
def load(self, path: Path | str) -> None:
    """Merge positions from a JSON file into ``positions``.

    Existing labels are overwritten by entries from *path*; labels
    absent in *path* are preserved.

    Args:
        path: Source JSON file previously written by [`save`][applied_motion.cli.session.MotionSession.save].

    Raises:
        OSError: If *path* cannot be opened.
        ValueError: If the file contains invalid JSON.
    """
    path = Path(path)
    with path.open() as fh:
        loaded: dict[str, dict[str, float]] = json.load(fh)
    self.positions.update(loaded)
    logger.info("MotionSession.load: read %d position(s) from %s", len(loaded), path)