Files
bambuddy/backend/app/schemas/spool.py
maziggy a7b563334e Configure a spool's filament preset and K profile per nozzle
A slicer preset is bound to a printer model: "Bambu PLA Basic @BBL X1C" is
not the same preset as "@BBL H2C", and Bambu names a nozzle size in it as
well. A spool carried exactly one, which was right until the same spool was
used on a second machine -- the AMS slot on the other one was then
configured with a preset that machine has no profile for. K profiles had
the matching gap from the other side: the tables have always been keyed per
hotend, but the picker could not express it.

spool_filament_preset and its Spoolman twin store the exceptions, keyed
(spool, printer_model, nozzle_diameter). Model rather than printer because
the preset is a property of the model -- "@BBL X1C" is the same preset on
every X1C, and asking per machine would mean picking the identical value
twice. K profiles stay on printer_id, because a K value is measured on one
physical hotend and two machines of the same model legitimately differ.
Resolution is exact (model, diameter) -> (model, "") -> the spool's own
preset, so a spool nobody has configured behaves exactly as it did before.
The form writes one row per nozzle size and never the "" row; that level is
kept for API clients wanting one value to cover a model.

Both halves cover every standard nozzle size rather than the size currently
fitted, because a spool is configured once and nozzles get swapped. The PA
Profile tab becomes a Printers tab: a model list beside a detail pane
holding a preset row per size and a K-profile grid of size by hotend. Each
model is offered only the presets that name it, through the same matcher
the Configure AMS Slot modal filters with, which moves out of that
component into utils/slicerPrinterMatch. Presets whose name identifies no
model -- most user-authored and OrcaSlicer ones -- stay offered everywhere,
as does whatever is already selected, so a saved override cannot vanish
from the control that shows it. Every preset carries an origin badge in the
wording and colours that modal already uses.

Every path that configures a slot now respects both: manual assign in
either inventory mode, RFID auto-assign, the Spoolman tag link, the re-fire
when a slot goes empty to loaded, the re-apply after a calibration-table
refresh, and the re-selection when a Filament Track Switch moves an AMS to
the other nozzle. Which nozzle a slot feeds, and how wide it is, was worked
out independently in seven of those places, each reading nozzles[0] for
every slot on the machine -- correct on a single-nozzle printer and on a
dual-nozzle printer with matching nozzles, wrong the moment two sizes are
fitted. That resolution is now services/slot_nozzle.

Which array entry belongs to which hotend is no longer inferred. Measured
on an H2D fitted with a 0.4 high flow on the left and a 0.6 on the right,
nozzles[0] reads the right hotend, so the array is indexed by extruder id
and the H2/X2 parser's convention is the one that holds. The legacy
parser's opposite convention never governs a real dual-nozzle machine:
every model in DUAL_NOZZLE_MODELS reports device.nozzle.info, and
left_nozzle_diameter appears in no log or wire capture. Two comments that
said otherwise were wrong and are fixed; amsHelpers' code was right all
along and only its comment lied.

Four defects surfaced while wiring it, all pre-existing except the last.
The picker identified a chosen calibration by cali_idx alone, and the
printer numbers its calibration table per nozzle -- on a dual-nozzle
machine the same index exists on both hotends meaning different things, so
saving could persist the other hotend's K value and diameter; SpoolBuddy's
write-tag page carried a verbatim copy and gets the same fix. RFID
auto-assign chose a K profile with no extruder test at all, so a spool
calibrated on both hotends had a coin toss decide which pressure-advance
value the slot got, on the path that runs unattended every time a Bambu
spool is loaded. The Spoolman tag-link path resolved no preset whatsoever,
configuring every linked slot with a generic material id and discarding a
preset set in inventory -- the same defect #1713 fixed on the assign path,
one function over. And an FTS inlet move re-selected K for nozzle 0 rather
than for the nozzle the AMS had just been moved to.

The last one is new here: a per-model override can be a cloud USER preset,
whose PFUS-prefixed id the slicer rejects, and passing it straight into
extrusion_cali_sel would silently lose the K-profile link. Reached the
printer only where such an override exists, which is why nothing in the
suite caught it. printer_safe_filament_id falls through to the spool's own
preset and then the tray's RFID value instead.

Reading a printer's calibration table asks for one nozzle size at a time.
H2-series firmware answers only the first one or two of a concurrent burst
of extrusion_cali_get and silently drops the rest, each dropped request
costing a five-second timeout before its retry: measured at 11 and 23
seconds on an H2C and an H2D for four parallel requests, against roughly
one second in series. An X1C answers all four at once, which is why this
only ever surfaced on dual-diameter printers. Printers themselves are read
in parallel -- separate machines are separate connections.

The Configure AMS Slot dialog opens on the spool's own configured values,
falling back to the slot's last manual configuration and then the tray's
RFID data. The spool form is wider for the two-pane layout, colour, weight,
cost and location move to their own tab in two columns, and a printer card
in expanded view lists every fitted nozzle size rather than the first entry
alone.
2026-08-27 13:03:15 +02:00

273 lines
9.3 KiB
Python

from datetime import datetime
from pydantic import BaseModel, Field, field_validator
# Visual variant applied to a spool's swatch — purely cosmetic, does not
# affect MQTT/firmware. Kept independent of `subtype` so users can override
# the rendering hint without touching Bambu's categorical filament label.
# Mirrors the visual variants the spool form's `KNOWN_VARIANTS` exposes so
# the catalog and spool form share one vocabulary; structural variants like
# gradient/dual-color/tri-color/multicolor combine with `extra_colors` for
# rendering, surface effects (sparkle/wood/marble/glow/matte) layer overlays.
ALLOWED_EFFECT_TYPES = frozenset(
{
# Surface effects
"sparkle",
"wood",
"marble",
"glow",
"matte",
# Sheen / finish variants
"silk",
"galaxy",
"rainbow",
"metal",
"translucent",
# Multi-colour structures (drive gradient rendering when paired with extra_colors)
"gradient",
"dual-color",
"tri-color",
"multicolor",
}
)
# Cap how many gradient stops we accept on input so a paste of arbitrary text
# can't blow up the stored value or downstream rendering.
MAX_EXTRA_COLOR_STOPS = 8
def normalize_extra_colors(value: str | None) -> str | None:
"""Parse comma-separated hex tokens into canonical lowercase form.
Accepts 6- or 8-char hex per token, with or without leading `#`. Returns
None for blank input, raises ValueError for malformed tokens or too many
stops. Output is the comma-joined canonical form (no `#`, lowercase).
"""
if value is None:
return None
raw = value.strip()
if not raw:
return None
tokens = [tok.strip().lstrip("#").lower() for tok in raw.split(",") if tok.strip()]
if not tokens:
return None
if len(tokens) > MAX_EXTRA_COLOR_STOPS:
raise ValueError(f"extra_colors accepts at most {MAX_EXTRA_COLOR_STOPS} stops")
for tok in tokens:
if len(tok) not in (6, 8):
raise ValueError(f"extra_colors token '{tok}' must be 6 or 8 hex chars")
try:
int(tok, 16)
except ValueError as exc:
raise ValueError(f"extra_colors token '{tok}' is not valid hex") from exc
return ",".join(tokens)
def normalize_effect_type(value: str | None) -> str | None:
if value is None:
return None
trimmed = value.strip().lower()
if not trimmed:
return None
# Tolerate "Dual Color" / "dual_color" / "dual color" → "dual-color" so
# users pasting from spool-subtype labels don't hit a validation wall.
canonical = trimmed.replace("_", "-").replace(" ", "-")
if canonical not in ALLOWED_EFFECT_TYPES:
raise ValueError(f"effect_type must be one of: {sorted(ALLOWED_EFFECT_TYPES)}")
return canonical
class SpoolBase(BaseModel):
material: str = Field(..., min_length=1, max_length=50)
subtype: str | None = None
color_name: str | None = None
rgba: str | None = Field(None, pattern=r"^[0-9A-Fa-f]{8}$")
extra_colors: str | None = None
effect_type: str | None = None
brand: str | None = None
@field_validator("extra_colors")
@classmethod
def _validate_extra_colors(cls, v: str | None) -> str | None:
return normalize_extra_colors(v)
@field_validator("effect_type")
@classmethod
def _validate_effect_type(cls, v: str | None) -> str | None:
return normalize_effect_type(v)
label_weight: int = 1000
core_weight: int = 250
core_weight_catalog_id: int | None = None
weight_used: float = 0
# Anchor for the resettable "Total Consumed" display. The Inventory
# page shows `weight_used - weight_used_baseline`; the per-spool /
# bulk "Reset usage to 0" action sets baseline = weight_used so the
# counter zeroes without touching remaining (#1390).
weight_used_baseline: float = 0
slicer_filament: str | None = None
slicer_filament_name: str | None = None
nozzle_temp_min: int | None = None
nozzle_temp_max: int | None = None
note: str | None = None
tag_uid: str | None = None
tray_uuid: str | None = None
data_origin: str | None = None
tag_type: str | None = None
cost_per_kg: float | None = Field(default=None, ge=0)
weight_locked: bool = False
last_scale_weight: int | None = None
last_weighed_at: datetime | None = None
# User-defined category + per-spool low-stock threshold override (#729).
category: str | None = Field(default=None, max_length=50)
low_stock_threshold_pct: int | None = Field(default=None, ge=1, le=99)
# Free-text storage location, distinct from `location` (AMS slot
# assignment). Column has lived on the ORM since the inventory rework
# but was missing from this schema, so writes were silently dropped (#1291).
storage_location: str | None = Field(default=None, max_length=255)
location_id: int | None = Field(default=None, gt=0)
class SpoolCreate(SpoolBase):
pass
class SpoolBulkCreate(BaseModel):
spool: SpoolCreate
quantity: int = Field(default=1, ge=1, le=100)
class SpoolUpdate(BaseModel):
material: str | None = None
subtype: str | None = None
color_name: str | None = None
rgba: str | None = Field(None, pattern=r"^[0-9A-Fa-f]{8}$")
extra_colors: str | None = None
effect_type: str | None = None
brand: str | None = None
@field_validator("extra_colors")
@classmethod
def _validate_extra_colors(cls, v: str | None) -> str | None:
return normalize_extra_colors(v)
@field_validator("effect_type")
@classmethod
def _validate_effect_type(cls, v: str | None) -> str | None:
return normalize_effect_type(v)
label_weight: int | None = None
core_weight: int | None = None
core_weight_catalog_id: int | None = None
weight_used: float | None = None
slicer_filament: str | None = None
slicer_filament_name: str | None = None
nozzle_temp_min: int | None = None
nozzle_temp_max: int | None = None
note: str | None = None
tag_uid: str | None = None
tray_uuid: str | None = None
data_origin: str | None = None
tag_type: str | None = None
cost_per_kg: float | None = Field(default=None, ge=0)
weight_locked: bool | None = None
# User-defined category + per-spool low-stock threshold override (#729).
category: str | None = Field(default=None, max_length=50)
low_stock_threshold_pct: int | None = Field(default=None, ge=1, le=99)
storage_location: str | None = Field(default=None, max_length=255)
location_id: int | None = Field(default=None, gt=0)
class SpoolKProfileBase(BaseModel):
printer_id: int
extruder: int = 0
nozzle_diameter: str = "0.4"
nozzle_type: str | None = None
k_value: float
name: str | None = None
cali_idx: int | None = None
setting_id: str | None = None
class SpoolKProfileResponse(SpoolKProfileBase):
id: int
spool_id: int
created_at: datetime
class Config:
from_attributes = True
class SpoolFilamentPresetBase(BaseModel):
"""One per-printer-model slicer preset override for a spool.
``nozzle_diameter`` defaults to "" meaning "any nozzle of this model". The
spool form always sends a concrete size; the empty form is for API clients
that want one value to cover a model. Lengths match the columns, which are wider than
``Spool.slicer_filament`` so a preset id that fits the Spoolman write
schema cannot truncate on the way in.
"""
printer_model: str = Field(..., min_length=1, max_length=50)
nozzle_diameter: str = Field(default="", max_length=10)
slicer_filament: str | None = Field(default=None, max_length=128)
slicer_filament_name: str | None = Field(default=None, max_length=255)
class SpoolFilamentPresetResponse(SpoolFilamentPresetBase):
id: int
spool_id: int
created_at: datetime
class Config:
from_attributes = True
class SpoolResponse(SpoolBase):
id: int
# rgba is intentionally unconstrained on the response side: the write paths
# (SpoolCreate, SpoolUpdate) enforce the 8-char hex pattern, but legacy rows
# or data sourced from AMS firmware / backups may carry malformed values.
# A single bad row must not 500 the entire inventory list endpoint (#1055).
rgba: str | None = None
added_full: bool | None = None
last_used: datetime | None = None
encode_time: datetime | None = None
tag_uid: str | None = None
tray_uuid: str | None = None
data_origin: str | None = None
tag_type: str | None = None
archived_at: datetime | None = None
created_at: datetime
updated_at: datetime
k_profiles: list[SpoolKProfileResponse] = []
class Config:
from_attributes = True
class SpoolAssignmentCreate(BaseModel):
spool_id: int
printer_id: int
ams_id: int
tray_id: int
class SpoolAssignmentResponse(BaseModel):
id: int
spool_id: int
printer_id: int
printer_name: str | None = None
ams_id: int
tray_id: int
fingerprint_color: str | None = None
fingerprint_type: str | None = None
created_at: datetime
spool: SpoolResponse | None = None
configured: bool = False
pending_config: bool = False # True when slot was empty at assign time; will configure on insert
ams_label: str | None = None # User-defined friendly name for the AMS unit
class Config:
from_attributes = True