From bb64d0a54604e81dcf53fb02eb24c4eeef4d94f2 Mon Sep 17 00:00:00 2001 From: Yang Cao Date: Thu, 5 Nov 2026 04:15:41 +0000 Subject: [PATCH] feat: position_bed control verb for the Bambu A1 (approved 2026-11-05) Yang approved a fifth control verb for the A1 only, so the camera can see the whole plate before a plate check after the bed was parked forward for pickup, and so the bed can be returned to the pickup position. POST /printers/{id}/control/position_bed takes {"position": "inspect" | "pickup", "bed_path_clear": true} and moves the bed to the Y configured under the printer's `bed_positions`. It sends exactly `G90` / `G1 Y F` through the backend: no X, no Z, no homing, no caller-supplied coordinate. Gates: claim; idle, error-free printer with no gateway job in flight; edge-verified caller; an agent also needs agent mode on. Config accepts `bed_positions` on an A1 only. Each move emits `bed.moved`; a refused or undelivered move is never retried. AGENTS.md and AGENT_RULES.md rule 1 record the approval. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 8 +- AGENT_RULES.md | 11 +- README.md | 16 +- docs/API_REFERENCE.md | 7 +- printers.example.yaml | 6 + src/bambu_server/agent_workflow.py | 1 + src/bambu_server/backend.py | 22 +++ src/bambu_server/config.py | 32 ++++ src/bambu_server/dispatch.py | 149 +++++++++++++++++ src/bambu_server/docs/AGENT_GUIDE.md | 9 ++ src/bambu_server/main.py | 52 +++++- tests/conftest.py | 7 + tests/test_position_bed.py | 232 +++++++++++++++++++++++++++ 13 files changed, 544 insertions(+), 8 deletions(-) create mode 100644 tests/test_position_bed.py diff --git a/AGENTS.md b/AGENTS.md index 37c7533..745771c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,13 @@ camera snapshot that the plate is empty (`agent_camera`). Every other printer, and the A1 with the switch off, keeps the human-in-the-loop rules unchanged; see `AGENT_RULES.md` rule 4. The same day, robot calibration was ruled out of scope: the gateway reports object positions in bed millimetres and the arm agent owns -the transform. All printer commands go through `bambu_server.dispatch` and +the transform. On 2026-11-05 Yang approved (in a Claude Code session, recorded +in this change) a fifth verb, **`position_bed`, for the Bambu A1 only**: a +Y-only move of the bed to one of two configured positions -- `inspect`, where +the camera sees the whole plate, and `pickup`, where the arm takes parts off -- +on an idle printer, under the claim, with a verified caller (an agent also +needs agent mode on) who states `bed_path_clear: true`. No X, no Z, no homing, +no caller-supplied coordinate; never retried. See `AGENT_RULES.md` rule 1. All printer commands go through `bambu_server.dispatch` and the backend's control methods; nothing else may call `bambulabs_api` command methods. Adding a verb, relaxing a gate, or letting an agent start a print without a person anywhere beyond that A1 approval needs a new explicitly diff --git a/AGENT_RULES.md b/AGENT_RULES.md index 268637b..afdf23b 100644 --- a/AGENT_RULES.md +++ b/AGENT_RULES.md @@ -12,7 +12,16 @@ the Bambu printer gateway. the stock start gcode's bed-mesh `M500` right after `G29` accepted -- every other refused command still refused), and `stop_print`, all behind `dispatch.enabled` and the gates in - `bambu_server.dispatch`. Any other verb, a relaxed gate, or integration with + `bambu_server.dispatch`. **Added 2026-11-05, approved by Yang, Bambu A1 + only:** `position_bed`, which moves the bed (Y axis only, absolute `G90` / + `G1 Y.. F..`, nothing else) to a configured `inspect` or `pickup` position + (`bed_positions` on the printer, accepted by config on an A1 only). It needs + the claim, an idle printer in no error state with no job in flight, an + edge-verified caller -- an agent also needs the A1's agent mode on -- and the + caller's statement `bed_path_clear: true` that no robot arm, hand or object + is in the bed's travel or above the plate. The caller names a position, + never a coordinate; a refused or undelivered move is never retried and is + never "fixed" by homing. Any other verb, a relaxed gate, or integration with `lab-skills` plan execution needs a new, explicitly approved design. 2. Monitoring must never start, pause, resume, stop, heat, home, move, calibrate, upload to, or otherwise control a printer. diff --git a/README.md b/README.md index 4d419ce..681d808 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,8 @@ a printer. By default the service is **monitoring-only** and exposes no control endpoints. A deployment that sets `dispatch.enabled` gets a narrow control plane: claims -plus four verbs (camera snapshot, chamber light, start an approved job, stop), +plus five verbs (camera snapshot, chamber light, start an approved job, stop, +and — on the Bambu A1 only — moving the bed to a named position), behind the gates described in [Control plane](#control-plane). A person confirms the plate is empty before every start, except on a printer whose **agent mode** an admin has switched on — approved 2026-11-02 for the Bambu A1 @@ -489,7 +490,7 @@ Slicing and submission do not claim, upload to, or start the physical printer. ### Control plane Off unless `dispatch.enabled` is set. When on, each printer gets STATUS_SPEC -v1.1 claims and four verbs under `/printers/{id}/control/`: +v1.1 claims and five verbs under `/printers/{id}/control/`: | Route | What it does | |---|---| @@ -498,6 +499,17 @@ v1.1 claims and four verbs under `/printers/{id}/control/`: | `light` | Switch the chamber light (`{"on": true}`), e.g. before a snapshot. No motion, no heat. | | `start_print` | Upload an approved job's `.3mf` and start it. | | `stop_print` | Stop the job in flight. | +| `position_bed` | Bambu A1 only (approved 2026-11-05): move the bed to `inspect` (camera sees the whole plate) or `pickup` (where the arm takes parts). | + +`position_bed` takes `{"position": "inspect" | "pickup", "bed_path_clear": true}` +and moves the bed to the Y configured under the printer's `bed_positions` +(`inspect_y_mm`, `pickup_y_mm`; keep `pickup_y_mm` equal to the slicer's +`end_bed_y_mm`). It sends exactly `G90` / `G1 Y F` -- no X, no Z, no +homing -- and is refused (412) unless the printer is idle, error-free and not +running a gateway job; it needs an edge-verified caller, and an agent also needs +agent mode on. Each move emits a `bed.moved` event. The printer does not report +bed position, so confirm it with a snapshot; a refused or undelivered move +(502) is never retried. Config accepts `bed_positions` on an A1 only. `start_print` is refused (412, a body naming the failed gate) unless the printer is observable, idle, not in a failed state and cold (`safe_bed_c`, diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 33338ab..1ae9e96 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -26,7 +26,7 @@ the routes enabled in a deployment. | Per-printer reads | `GET /printers/{id}/`, `/health`, `/status`, `/profile`, `/queue` | | Submit and review | `POST /submissions`; `GET /submissions`, `/submissions/{id}`; `POST /submissions/{id}/approve`, `/cancel` | | Claims (dispatch enabled) | `POST /printers/{id}/control/claim`, `/heartbeat`, `/release` | -| Printer I/O (dispatch enabled) | `POST /printers/{id}/control/snapshot`, `/light`, `/start_print`, `/stop_print` | +| Printer I/O (dispatch enabled) | `POST /printers/{id}/control/snapshot`, `/light`, `/start_print`, `/stop_print`, `/position_bed` (A1 only) | | View-only camera (dispatch enabled) | `GET /printers/{id}/camera.jpg` | | Agent switch | `GET /printers/{id}/agent-mode`; `POST` on that path is admin-only, never agent-operated | | Completion and pickup | `GET /events`, `/submissions/{id}/objects`, `/submissions/{id}/pickup-targets` | @@ -101,7 +101,10 @@ not establish a filament-to-slot mapping or sufficient remaining quantity. Per printer, under `/printers/{id}/control/`: `claim`, `heartbeat`, `release` (STATUS_SPEC §5), then `snapshot`, `light` (`{"on": true|false}`), -`start_print`, `stop_print`, each requiring +`start_print`, `stop_print` and, on the Bambu A1 only, `position_bed` +(`{"position": "inspect"|"pickup", "bed_path_clear": true}`: a Y-only move to a +configured position on an idle printer; verified caller, agent mode for an +agent; emits `bed.moved`; never retried), each requiring `X-Claim-Token` (423 without it). `start_print` takes the approved `submission_id`, `plate_confirmed_empty: true`, `plate_check_method` (`printer_camera` with a `snapshot_token`, `in_person`, or — for an agent on a diff --git a/printers.example.yaml b/printers.example.yaml index abb0e0a..f2c0d8c 100644 --- a/printers.example.yaml +++ b/printers.example.yaml @@ -120,6 +120,12 @@ printers: # (POST /printers/bambu_a1_01/agent-mode). The switch itself starts off. # Accepted on a Bambu A1 only; any other model fails config validation. agent_mode_eligible: true + # Named bed positions for POST /control/position_bed (approved 2026-11-05, + # A1 only): `inspect` where the camera sees the whole plate, `pickup` where + # the arm takes parts off (keep equal to the slicer's end_bed_y_mm). + # bed_positions: + # inspect_y_mm: 128 + # pickup_y_mm: 250 profile: enclosure: open nozzle_diameter_mm: 0.4 diff --git a/src/bambu_server/agent_workflow.py b/src/bambu_server/agent_workflow.py index ee04a65..0e5b634 100644 --- a/src/bambu_server/agent_workflow.py +++ b/src/bambu_server/agent_workflow.py @@ -34,6 +34,7 @@ "job.cancelled", "job.cooled", "gateway.restarted", + "bed.moved", ] #: Terminal job state to the event announcing it. diff --git a/src/bambu_server/backend.py b/src/bambu_server/backend.py index ba95c26..487741b 100644 --- a/src/bambu_server/backend.py +++ b/src/bambu_server/backend.py @@ -178,6 +178,8 @@ def stop_print(self) -> None: ... def set_chamber_light(self, on: bool) -> None: ... + def move_bed_y(self, y_mm: float, feed_mm_min: int) -> None: ... + def current_job_file(self) -> str | None: ... def snapshot(self, timeout_s: float = 10.0) -> bytes: ... @@ -335,6 +337,26 @@ def set_chamber_light(self, on: bool) -> None: } ) + def move_bed_y(self, y_mm: float, feed_mm_min: int) -> None: + """Move the Y axis only (on a bed-slinger, the bed), in absolute mode. + + Exactly two gcode lines, built here from numbers: no X, no Z, no + homing, no heat, no extrusion. Approved 2026-11-05 for the A1's + ``position_bed`` verb; :mod:`bambu_server.dispatch` gates every call. + """ + + if not (0 <= y_mm <= 256) or not (300 <= feed_mm_min <= 6000): + raise PrinterCommandError("bed move out of range") + self._publish( + { + "print": { + "command": "gcode_line", + "param": f"G90\nG1 Y{y_mm:.1f} F{int(feed_mm_min)}\n", + "sequence_id": "10000002", + } + } + ) + def current_job_file(self) -> str | None: """The file the printer says it is printing, from the cached telemetry.""" diff --git a/src/bambu_server/config.py b/src/bambu_server/config.py index 6dc8567..d358383 100644 --- a/src/bambu_server/config.py +++ b/src/bambu_server/config.py @@ -111,6 +111,25 @@ def validate_bed(cls, value: tuple[float, float] | None) -> tuple[float, float] BedPlate = Literal["cool_plate", "eng_plate", "hot_plate", "textured_plate", "supertack_plate"] +class BedPositions(BaseModel): + """Named Y positions the ``position_bed`` verb may park a bed-slinger at. + + Approved by Yang on 2026-11-05 for the Bambu A1 only. The caller names a + position, never a coordinate: ``inspect`` is where the camera sees the + whole plate (for the plate check), ``pickup`` where the robot arm takes + parts off (keep it equal to the slicer's ``end_bed_y_mm``). + """ + + inspect_y_mm: float = Field(ge=0, le=256) + pickup_y_mm: float = Field(ge=0, le=256) + #: Feed rate of the move, mm/min. 3000 (50 mm/s) is gentler than the + #: A1's own end-gcode park move (3600). + feed_mm_min: int = Field(default=3000, ge=300, le=6000) + + def y_for(self, position: str) -> float: + return self.inspect_y_mm if position == "inspect" else self.pickup_y_mm + + class PrinterDefinition(BaseModel): id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") name: str = Field(min_length=1, max_length=120) @@ -120,6 +139,9 @@ class PrinterDefinition(BaseModel): #: Whether an admin may switch agent mode on for this printer at runtime. #: Approved 2026-11-02 for the Bambu A1 only; refused on any other model. agent_mode_eligible: bool = False + #: Named bed positions for ``position_bed`` (approved 2026-11-05 for the + #: Bambu A1 only). Absent means the verb is refused on this printer. + bed_positions: BedPositions | None = None @field_validator("id", "name", "model", "env_prefix", mode="before") @classmethod @@ -134,6 +156,16 @@ def agent_mode_only_on_a1(self) -> PrinterDefinition: raise ValueError( f"agent_mode_eligible is approved for Bambu A1 printers only, not {self.model!r}" ) + if self.bed_positions is not None and not model_is_agent_mode_capable(self.model): + raise ValueError( + f"bed_positions (position_bed) is approved for Bambu A1 printers only, " + f"not {self.model!r}" + ) + bed = self.profile.bed_size_mm + if self.bed_positions is not None and bed is not None: + for name in ("inspect_y_mm", "pickup_y_mm"): + if getattr(self.bed_positions, name) > bed[1]: + raise ValueError(f"bed_positions.{name} is beyond the {bed[1]:g} mm bed") return self diff --git a/src/bambu_server/dispatch.py b/src/bambu_server/dispatch.py index f454140..d099c3f 100644 --- a/src/bambu_server/dispatch.py +++ b/src/bambu_server/dispatch.py @@ -14,6 +14,12 @@ step that ends without the printer settling the question is ``failed`` with the uncertainty written down. Nothing here retries. +``position_bed`` (approved by Yang on 2026-11-05, Bambu A1 only) moves the bed +between two configured Y positions -- ``inspect`` so the camera sees the whole +plate, ``pickup`` for the robot arm -- on an idle printer, under the claim, with +the caller's affirmative statement that nothing is in the bed's path. It is a +Y-only move: no X, no Z, no homing. + Refusals never touch ``last_error`` (STATUS_SPEC §6.3). """ @@ -114,6 +120,32 @@ class LightResponse(BaseModel): note: str = "command delivered; the printer's light_state in /status confirms it" +BedPosition = Literal["inspect", "pickup"] + + +class PositionBedRequest(BaseModel): + position: BedPosition + #: Must be literally true: the caller states that no robot arm, hand or + #: object is in the bed's travel or standing above the plate. + bed_path_clear: Literal[True] + moved_by: str | None = Field(default=None, min_length=1, max_length=120) + reason: str | None = Field(default=None, max_length=500) + + +class PositionBedResponse(BaseModel): + printer_id: str + position: BedPosition + y_mm: float + requested_at: datetime + moved_by: str + moved_by_verified: bool + agent_id: str | None = None + note: str = ( + "command delivered; the printer does not report bed position, so confirm " + "it with a camera snapshot before relying on it" + ) + + class StopPrintResponse(BaseModel): printer_id: str stop_requested_at: datetime @@ -215,12 +247,59 @@ def light_blockers(self, monitor: PrinterMonitor) -> list[dict[str, object]]: ] return [] + def position_bed_blockers( + self, monitor: PrinterMonitor, *, busy_with_dispatch: bool + ) -> list[dict[str, object]]: + """Only an idle, error-free printer with configured positions moves its bed.""" + + if monitor.definition.bed_positions is None: + return [ + { + "detail": "position_bed is not configured for this printer " + "(approved for the Bambu A1 only)", + "bed_positions": None, + } + ] + status = monitor.status() + if status.activity == "unknown": + return [ + { + "detail": "printer state is not determinable (telemetry missing or stale)", + "activity": "unknown", + "retry_after_s": 10, + } + ] + blockers: list[dict[str, object]] = [] + if status.activity != "idle": + blockers.append( + {"detail": "the bed only moves on an idle printer", "activity": status.activity} + ) + if status.equipment_status == "error": + blockers.append( + { + "detail": "the printer reports an error; clear it on the printer first", + "equipment_status": "error", + } + ) + if busy_with_dispatch: + blockers.append( + { + "detail": "the gateway is tracking a job on this printer", + "gateway_job_in_flight": True, + } + ) + return blockers + def allowed_actions(self, monitor: PrinterMonitor, *, busy_with_dispatch: bool) -> list[str]: if not self.settings.enabled: return [] actions = ["snapshot"] if not self.light_blockers(monitor): actions.append("light") + if monitor.definition.bed_positions is not None and not self.position_bed_blockers( + monitor, busy_with_dispatch=busy_with_dispatch + ): + actions.append("position_bed") if not self.start_print_blockers(monitor, busy_with_dispatch=busy_with_dispatch): actions.append("start_print") if not self.stop_print_blockers(monitor): @@ -709,6 +788,76 @@ async def light( raise ControlRefusal(502, {"detail": f"light command not delivered: {exc}"}) from exc return LightResponse(printer_id=printer_id, on=request.on, requested_at=datetime.now(UTC)) + # -- position_bed -------------------------------------------------------- + + async def position_bed( + self, + printer_id: str, + request: PositionBedRequest, + *, + actor: Actor, + agent: AgentCaller, + claim_token: str | None, + ) -> PositionBedResponse: + """Move the bed to a named position. Never retried; never homes.""" + + control = self._control(printer_id) + self.require_claim(printer_id, claim_token) + monitor = self._monitors[printer_id] + positions = monitor.definition.bed_positions + if positions is None: + raise ControlRefusal( + 412, self.gate.position_bed_blockers(monitor, busy_with_dispatch=False)[0] + ) + who, verified = self._identity(actor, request.moved_by) + if self.settings.require_verified_identity and not verified: + raise ControlRefusal( + 403, {"detail": "moving the bed requires an edge-verified identity"} + ) + if agent.is_agent: + if self._agent_mode is None: + raise ControlRefusal( + 403, {"detail": "agent bed moves are not available", "agent_mode": "not_eligible"} + ) + try: + self._agent_mode.require(printer_id, "bed move") + except AgentModeRefusal as exc: + raise ControlRefusal(exc.status, exc.body) from exc + if control.lock.locked(): + raise ControlRefusal( + 412, {"detail": "another control step is in progress on this printer"} + ) + async with control.lock: + blockers = self.gate.position_bed_blockers( + monitor, busy_with_dispatch=self.busy(printer_id) + ) + if blockers: + raise ControlRefusal(412, {**blockers[0], "blockers": blockers}) + y_mm = positions.y_for(request.position) + try: + await asyncio.to_thread( + self._backends[printer_id].move_bed_y, y_mm, positions.feed_mm_min + ) + except PrinterCommandError as exc: + raise ControlRefusal( + 502, {"detail": f"bed move not delivered: {exc}; check the printer, do not retry"} + ) from exc + logger.info( + "Bed on %s moved to %s (Y%.1f) by %s%s%s", + printer_id, request.position, y_mm, who, + " (verified identity)" if verified else "", + f" as agent {agent.agent_id}" if agent.is_agent else "", + ) + return PositionBedResponse( + printer_id=printer_id, + position=request.position, + y_mm=y_mm, + requested_at=datetime.now(UTC), + moved_by=who, + moved_by_verified=verified, + agent_id=agent.agent_id if agent.is_agent else None, + ) + # -- helpers ----------------------------------------------------------- def _identity(self, actor: Actor, supplied: str | None) -> tuple[str, bool]: diff --git a/src/bambu_server/docs/AGENT_GUIDE.md b/src/bambu_server/docs/AGENT_GUIDE.md index 7221251..ccb715c 100644 --- a/src/bambu_server/docs/AGENT_GUIDE.md +++ b/src/bambu_server/docs/AGENT_GUIDE.md @@ -101,6 +101,15 @@ stop command for a running print. 2. Read the printer's status and `allowed_actions`. These are current device preconditions, not a complete job-specific authorization. A listed `start_print` does not mean that the build plate is clear. + On the A1 the previous print leaves the bed parked forward for pickup, + where the camera cannot see the front of the plate. Before the snapshot, + move it into view: `POST /printers/bambu_a1_01/control/position_bed` with + `{"position": "inspect", "bed_path_clear": true}`. Send + `bed_path_clear: true` only after confirming the robot arm is parked clear + of the bed's travel and nothing stands above the plate. If the move is + refused or returns 502, stop and ask a person; never retry it. For pickup, + `{"position": "pickup", ...}` returns the bed to where the arm expects it + (`bed_park_y_mm` on `pickup-targets`). 3. Take `POST /printers/{id}/control/snapshot` under that claim. Inspect the returned image itself and retain its token. If an object is present, the plate is obscured, or the image is unclear, record occupied/unknown, diff --git a/src/bambu_server/main.py b/src/bambu_server/main.py index 031a700..68ae091 100644 --- a/src/bambu_server/main.py +++ b/src/bambu_server/main.py @@ -73,6 +73,8 @@ Dispatcher, LightRequest, LightResponse, + PositionBedRequest, + PositionBedResponse, SnapshotResponse, StartPrintRequest, StopPrintRequest, @@ -1384,7 +1386,9 @@ def get_camera() -> CameraViewer: return camera if control_enabled: - _register_control_routes(app, get_monitor, get_actor, get_dispatcher, get_agent) + _register_control_routes( + app, get_monitor, get_actor, get_dispatcher, get_agent, get_events + ) _register_camera_route(app, get_monitor, get_camera) if settings and settings.agent_workflow.vision_enabled: _register_advisory_bed_check(app, get_monitor, get_dispatcher, workflows) @@ -1488,8 +1492,9 @@ def _register_control_routes( get_actor: Callable[..., Actor], get_dispatcher: Callable[[], Dispatcher], get_agent: Callable[..., AgentCaller], + get_events: Callable[[], EventHub], ) -> None: - """STATUS_SPEC §5 claims plus the four control verbs, per printer. + """STATUS_SPEC §5 claims plus the control verbs, per printer. Only called when the local config enables dispatch, so a deployment that has not opted in exposes no ``/control/`` path at all. @@ -1643,6 +1648,49 @@ async def control_light( except ControlRefusal as exc: return _refusal(exc) + @app.post( + "/printers/{printer_id}/control/position_bed", + response_model=PositionBedResponse, + responses={ + 502: {"model": RefusalBody, "description": "Command not delivered."}, + **control_responses, + }, + tags=["control"], + ) + async def control_position_bed( + monitor: Annotated[PrinterMonitor, Depends(get_monitor)], + actor: Annotated[Actor, Depends(get_actor)], + agent: Annotated[AgentCaller, Depends(get_agent)], + dispatcher: Annotated[Dispatcher, Depends(get_dispatcher)], + events: Annotated[EventHub, Depends(get_events)], + request: PositionBedRequest, + claim_token: Annotated[str | None, Header(alias=CLAIM_HEADER)] = None, + ) -> PositionBedResponse | JSONResponse: + """Move the bed to a named position: ``inspect`` (the camera sees the + whole plate) or ``pickup`` (where the arm takes parts off). + + Approved 2026-11-05 for the Bambu A1 only. Needs the claim, an idle + printer, a verified identity (an agent also needs agent mode on), and + ``bed_path_clear: true``. A Y-only move -- no X, no Z, no homing. The + printer does not report bed position: confirm it with a snapshot. + Never retry a refused or undelivered move; check the printer first. + """ + + try: + moved = await dispatcher.position_bed( + monitor.definition.id, request, actor=actor, agent=agent, + claim_token=claim_token, + ) + except ControlRefusal as exc: + return _refusal(exc) + note = f"bed moved to {moved.position} (Y{moved.y_mm:g}) by {moved.moved_by}" + if moved.agent_id: + note += f" (agent {moved.agent_id})" + if request.reason: + note += f": {request.reason.strip()}" + await events.publish("bed.moved", printer_id=moved.printer_id, note=note[:500]) + return moved + @app.post( "/printers/{printer_id}/control/stop_print", response_model=StopPrintResponse, diff --git a/tests/conftest.py b/tests/conftest.py index ffb3644..5d5ac89 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -123,6 +123,8 @@ def __init__(self, reading: PrinterReading) -> None: self.start_commands: list[StartPrintCommand] = [] self.stop_calls = 0 self.light_calls: list[bool] = [] + self.bed_moves: list[tuple[float, int]] = [] + self.fail_bed_move = False self.snapshots = 0 self.fail_upload = False self.fail_snapshot = False @@ -164,6 +166,11 @@ def set_chamber_light(self, on: bool) -> None: self.light_calls.append(on) self.reading = replace(self.reading, light_state="on" if on else "off") + def move_bed_y(self, y_mm: float, feed_mm_min: int) -> None: + if self.fail_bed_move: + raise PrinterCommandError("the MQTT broker did not confirm the command") + self.bed_moves.append((y_mm, feed_mm_min)) + def current_job_file(self) -> str | None: return self.job_file diff --git a/tests/test_position_bed.py b/tests/test_position_bed.py new file mode 100644 index 0000000..87d0ddd --- /dev/null +++ b/tests/test_position_bed.py @@ -0,0 +1,232 @@ +"""position_bed: the A1-only bed move (approved 2026-11-05). + +Every printer is a :class:`FakeBackend`; nothing here can reach a printer. The +assertions that matter most are the negative ones -- when a gate closes, the +fake records no bed move. +""" + +from __future__ import annotations + +import time +from collections.abc import Iterator +from dataclasses import replace + +import pytest +from fastapi.testclient import TestClient +from pydantic import ValidationError + +from bambu_server.backend import BambuLabsBackend, PrinterCommandError +from bambu_server.config import PrinterDefinition, Settings +from bambu_server.main import create_app + +from .conftest import FakeBackend + +A1 = "bambu_a1_01" +X1 = "bambu_test_01" +EDGE = "test-edge-secret" +OPERATOR = {"X-Edge-Auth": EDGE, "X-Auth-User": "alice", "X-Auth-Role": "operator"} +ADMIN = {"X-Edge-Auth": EDGE, "X-Auth-User": "yang", "X-Auth-Role": "admin"} +AGENT = { + "X-Edge-Auth": EDGE, "X-Auth-User": "svc-print-agent", "X-Auth-Role": "agent", + "X-Agent-Id": "planner-7", +} +POSITIONS = {"inspect_y_mm": 128, "pickup_y_mm": 250} + + +def _settings(settings: Settings, monkeypatch) -> Settings: + monkeypatch.setenv("BAMBU_EDGE_SHARED_SECRET", EDGE) + for key in ("HOST", "ACCESS_CODE", "SERIAL"): + monkeypatch.setenv(f"BAMBU_A1_01_{key}", "secret") + payload = settings.model_dump(mode="json") + payload["poll_interval_seconds"] = 0.5 + payload["stale_after_seconds"] = 5.0 + first = payload["printers"][0] + first["model"] = "X1 Carbon" + first["profile"]["plate"] = "textured_plate" + payload["printers"].append({ + **first, "id": A1, "name": "Bambu A1 01", "model": "A1", "env_prefix": "BAMBU_A1_01", + "agent_mode_eligible": True, "bed_positions": POSITIONS, + "profile": {**first["profile"], "enclosure": "open"}, + }) + payload["dispatch"] = {"enabled": True, "require_verified_identity": True} + return Settings.model_validate(payload) + + +@pytest.fixture +def backends(reading) -> dict[str, FakeBackend]: + made = {X1: FakeBackend(reading), A1: FakeBackend(reading)} + for backend in made.values(): + backend.refresh_timestamps = True + return made + + +@pytest.fixture +def client(settings: Settings, backends, monkeypatch) -> Iterator[TestClient]: + app = create_app( + settings=_settings(settings, monkeypatch), + backend_factory=lambda definition, _c: backends[definition.id], + ) + with TestClient(app) as test_client: + yield test_client + + +def _claim(client: TestClient, printer: str, headers: dict) -> dict: + response = client.post( + f"/printers/{printer}/control/claim", + json={"owner": "x", "session_id": "s1"}, headers=headers, + ) + assert response.status_code == 200, response.text + return {**headers, "X-Claim-Token": response.json()["claim_token"]} + + +def _move(client: TestClient, headers: dict, printer: str = A1, **body: object): + payload = {"position": "inspect", "bed_path_clear": True, **body} + return client.post(f"/printers/{printer}/control/position_bed", json=payload, headers=headers) + + +def test_a_person_moves_the_a1_bed_to_a_named_position( + client: TestClient, backends: dict[str, FakeBackend] +) -> None: + headers = _claim(client, A1, OPERATOR) + assert "position_bed" in client.get(f"/printers/{A1}/status").json()["allowed_actions"] + + inspect = _move(client, headers, reason="camera check before the next start") + assert inspect.status_code == 200, inspect.text + assert inspect.json()["y_mm"] == 128 + assert inspect.json()["moved_by"] == "alice" and inspect.json()["moved_by_verified"] + pickup = _move(client, headers, position="pickup") + assert pickup.status_code == 200, pickup.text + + assert backends[A1].bed_moves == [(128, 3000), (250, 3000)] + backend = backends[A1] + assert backend.uploads == [] and backend.start_commands == [] and backend.stop_calls == 0 + events = [e for e in client.get("/events").json()["events"] if e["type"] == "bed.moved"] + assert [e["printer_id"] for e in events] == [A1, A1] + assert "inspect (Y128) by alice" in events[0]["note"] + assert "camera check" in events[0]["note"] + + +def test_a_move_needs_the_claim(client: TestClient, backends: dict[str, FakeBackend]) -> None: + response = _move(client, OPERATOR) + assert response.status_code == 423 + assert backends[A1].bed_moves == [] + + +@pytest.mark.parametrize( + "body", + [ + {"bed_path_clear": False}, + {"bed_path_clear": None}, + {"position": "home"}, + {"position": "inspect", "y_mm": 10}, # extra field ignored, but no raw Y is accepted + ], +) +def test_only_a_named_position_with_a_clear_path_is_accepted( + client: TestClient, backends: dict[str, FakeBackend], body: dict +) -> None: + headers = _claim(client, A1, OPERATOR) + response = _move(client, headers, **body) + if "y_mm" in body: + assert response.status_code == 200 + assert backends[A1].bed_moves == [(128, 3000)] # the configured Y, not the caller's + else: + assert response.status_code == 422 + assert backends[A1].bed_moves == [] + + +def test_an_unverified_caller_is_refused( + client: TestClient, backends: dict[str, FakeBackend] +) -> None: + claim = _claim(client, A1, OPERATOR) + response = _move(client, {"X-Claim-Token": claim["X-Claim-Token"]}, moved_by="mallory") + assert response.status_code == 403 + assert backends[A1].bed_moves == [] + + +def test_the_bed_does_not_move_on_a_busy_printer( + client: TestClient, backends: dict[str, FakeBackend] +) -> None: + backends[A1].reading = replace(backends[A1].reading, gcode_state="RUNNING", activity="PRINTING") + client.get(f"/printers/{A1}/status") + headers = _claim(client, A1, OPERATOR) + time.sleep(0.7) # let the monitor see the new state + assert "position_bed" not in client.get(f"/printers/{A1}/status").json()["allowed_actions"] + response = _move(client, headers) + assert response.status_code == 412 + assert "idle" in response.json()["detail"] + assert backends[A1].bed_moves == [] + + +def test_another_printer_has_no_bed_move( + client: TestClient, backends: dict[str, FakeBackend] +) -> None: + headers = _claim(client, X1, OPERATOR) + assert "position_bed" not in client.get(f"/printers/{X1}/status").json()["allowed_actions"] + response = _move(client, headers, printer=X1) + assert response.status_code == 412 + assert "Bambu A1 only" in response.json()["detail"] + assert backends[X1].bed_moves == [] + + +def test_an_agent_moves_the_bed_only_in_agent_mode( + client: TestClient, backends: dict[str, FakeBackend] +) -> None: + headers = _claim(client, A1, AGENT) + off = _move(client, headers) + assert off.status_code == 403 and off.json()["agent_mode"] == "off" + assert backends[A1].bed_moves == [] + + flipped = client.post( + f"/printers/{A1}/agent-mode", json={"enabled": True, "reason": "bed move test"}, + headers=ADMIN, + ) + assert flipped.status_code == 200, flipped.text + on = _move(client, headers) + assert on.status_code == 200, on.text + assert on.json()["agent_id"] == "planner-7" + assert backends[A1].bed_moves == [(128, 3000)] + + +def test_an_undelivered_move_is_reported_not_retried( + client: TestClient, backends: dict[str, FakeBackend] +) -> None: + backends[A1].fail_bed_move = True + headers = _claim(client, A1, OPERATOR) + response = _move(client, headers) + assert response.status_code == 502 + assert "do not retry" in response.json()["detail"] + assert backends[A1].bed_moves == [] + assert not [e for e in client.get("/events").json()["events"] if e["type"] == "bed.moved"] + + +def test_bed_positions_are_refused_off_the_a1() -> None: + with pytest.raises(ValidationError, match="Bambu A1 printers only"): + PrinterDefinition( + id="p", name="P", model="P1S", env_prefix="P", bed_positions=POSITIONS + ) + with pytest.raises(ValidationError): + PrinterDefinition( + id="p", name="P", model="A1", env_prefix="P", + bed_positions={"inspect_y_mm": 128, "pickup_y_mm": 300}, + ) + with pytest.raises(ValidationError, match="beyond"): + PrinterDefinition( + id="p", name="P", model="A1", env_prefix="P", bed_positions=POSITIONS, + profile={"bed_size_mm": [256, 200]}, + ) + + +def test_the_backend_sends_a_y_only_absolute_move() -> None: + backend = BambuLabsBackend.__new__(BambuLabsBackend) + sent: list[dict] = [] + backend._publish = sent.append # type: ignore[method-assign] + backend.move_bed_y(128.0, 3000) + assert sent == [{"print": { + "command": "gcode_line", "param": "G90\nG1 Y128.0 F3000\n", "sequence_id": "10000002", + }}] + gcode = sent[0]["print"]["param"] + assert "X" not in gcode and "Z" not in gcode and "G28" not in gcode and "E" not in gcode + for bad in ((-1.0, 3000), (257.0, 3000), (128.0, 10000)): + with pytest.raises(PrinterCommandError): + backend.move_bed_y(*bad) + assert len(sent) == 1