mirror of
https://github.com/maziggy/bambuddy.git
synced 2026-09-30 11:12:35 +02:00
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.
235 lines
9.3 KiB
Python
235 lines
9.3 KiB
Python
"""Endpoints for the per-printer-model filament preset overrides.
|
|
|
|
GET /api/v1/inventory/spools/{id}/filament-presets
|
|
PUT /api/v1/inventory/spools/{id}/filament-presets
|
|
GET /api/v1/spoolman/inventory/spools/{id}/filament-presets
|
|
PUT /api/v1/spoolman/inventory/spools/{id}/filament-presets
|
|
|
|
Both PUTs replace the whole set, matching the K-profile endpoints beside them:
|
|
the spool form always holds the complete list, and an empty body is how the
|
|
user clears every override back to the spool's own preset.
|
|
|
|
The case worth having a test for is the duplicate: (model, diameter) is
|
|
UNIQUE, so a payload naming one twice has to be refused -- and refused
|
|
*before* the existing rows are deleted, or a rejected save takes the user's
|
|
overrides with it.
|
|
"""
|
|
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
from httpx import AsyncClient
|
|
|
|
SAMPLE_SPOOL = {
|
|
"id": 7,
|
|
"filament": {
|
|
"id": 1,
|
|
"name": "PLA Basic",
|
|
"material": "PLA",
|
|
"weight": 1000,
|
|
"color_hex": "303030",
|
|
"vendor": {"id": 1, "name": "Bambu"},
|
|
},
|
|
"remaining_weight": 800.0,
|
|
"used_weight": 200.0,
|
|
"location": None,
|
|
"comment": None,
|
|
"first_used": None,
|
|
"last_used": None,
|
|
"registered": "2024-01-01T00:00:00+00:00",
|
|
"archived": False,
|
|
"price": None,
|
|
"extra": {},
|
|
}
|
|
|
|
INTERNAL = "/api/v1/inventory/spools"
|
|
SPOOLMAN = "/api/v1/spoolman/inventory/spools"
|
|
|
|
|
|
@pytest.fixture
|
|
async def spool(db_session):
|
|
from backend.app.models.spool import Spool
|
|
|
|
row = Spool(
|
|
brand="Bambu",
|
|
material="PLA",
|
|
color_name="Charcoal",
|
|
slicer_filament="GFSA00",
|
|
slicer_filament_name="Bambu PLA Basic @BBL X1C",
|
|
)
|
|
db_session.add(row)
|
|
await db_session.commit()
|
|
await db_session.refresh(row)
|
|
return row
|
|
|
|
|
|
@pytest.fixture
|
|
async def spoolman_settings(db_session):
|
|
from backend.app.models.settings import Settings
|
|
|
|
db_session.add(Settings(key="spoolman_enabled", value="true"))
|
|
db_session.add(Settings(key="spoolman_url", value="http://localhost:7912"))
|
|
await db_session.commit()
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_spoolman_client():
|
|
client = MagicMock()
|
|
client.base_url = "http://localhost:7912"
|
|
client.health_check = AsyncMock(return_value=True)
|
|
client.get_spool = AsyncMock(return_value=SAMPLE_SPOOL)
|
|
|
|
with patch(
|
|
"backend.app.api.routes.spoolman_inventory._get_client",
|
|
AsyncMock(return_value=client),
|
|
):
|
|
yield client
|
|
|
|
|
|
def _preset(model, diameter="", code="GFSA09", name="Bambu PLA Basic @BBL H2C"):
|
|
return {
|
|
"printer_model": model,
|
|
"nozzle_diameter": diameter,
|
|
"slicer_filament": code,
|
|
"slicer_filament_name": name,
|
|
}
|
|
|
|
|
|
@pytest.mark.integration
|
|
class TestInternalInventory:
|
|
@pytest.mark.asyncio
|
|
async def test_empty_by_default(self, async_client: AsyncClient, spool):
|
|
response = await async_client.get(f"{INTERNAL}/{spool.id}/filament-presets")
|
|
assert response.status_code == 200
|
|
assert response.json() == []
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_put_then_get_round_trips(self, async_client: AsyncClient, spool):
|
|
response = await async_client.put(
|
|
f"{INTERNAL}/{spool.id}/filament-presets",
|
|
json=[_preset("H2C"), _preset("A1 mini", "0.2", "GFSA21", "PLA @A1M 0.2 nozzle")],
|
|
)
|
|
assert response.status_code == 200, response.text
|
|
|
|
rows = (await async_client.get(f"{INTERNAL}/{spool.id}/filament-presets")).json()
|
|
assert len(rows) == 2
|
|
by_model = {r["printer_model"]: r for r in rows}
|
|
assert by_model["H2C"]["nozzle_diameter"] == ""
|
|
assert by_model["H2C"]["slicer_filament"] == "GFSA09"
|
|
assert by_model["A1 mini"]["nozzle_diameter"] == "0.2"
|
|
assert by_model["A1 mini"]["slicer_filament"] == "GFSA21"
|
|
assert all(r["spool_id"] == spool.id for r in rows)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_put_replaces_rather_than_appends(self, async_client: AsyncClient, spool):
|
|
await async_client.put(f"{INTERNAL}/{spool.id}/filament-presets", json=[_preset("H2C")])
|
|
await async_client.put(f"{INTERNAL}/{spool.id}/filament-presets", json=[_preset("X1C")])
|
|
|
|
rows = (await async_client.get(f"{INTERNAL}/{spool.id}/filament-presets")).json()
|
|
assert [r["printer_model"] for r in rows] == ["X1C"]
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_empty_body_clears_every_override(self, async_client: AsyncClient, spool):
|
|
await async_client.put(f"{INTERNAL}/{spool.id}/filament-presets", json=[_preset("H2C")])
|
|
|
|
response = await async_client.put(f"{INTERNAL}/{spool.id}/filament-presets", json=[])
|
|
assert response.status_code == 200
|
|
assert (await async_client.get(f"{INTERNAL}/{spool.id}/filament-presets")).json() == []
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_replacing_the_same_key_does_not_trip_the_unique_constraint(self, async_client: AsyncClient, spool):
|
|
"""Deletes and inserts land in one transaction, and SQLAlchemy is free
|
|
to order the INSERTs first. Re-saving the same (model, diameter) with a
|
|
new preset is the ordinary case -- the user changed their pick."""
|
|
await async_client.put(f"{INTERNAL}/{spool.id}/filament-presets", json=[_preset("H2C")])
|
|
|
|
response = await async_client.put(
|
|
f"{INTERNAL}/{spool.id}/filament-presets",
|
|
json=[_preset("H2C", "", "GFSA11", "Bambu PLA Matte @BBL H2C")],
|
|
)
|
|
assert response.status_code == 200, response.text
|
|
|
|
rows = (await async_client.get(f"{INTERNAL}/{spool.id}/filament-presets")).json()
|
|
assert len(rows) == 1
|
|
assert rows[0]["slicer_filament"] == "GFSA11"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_duplicate_key_is_rejected_without_losing_the_stored_rows(self, async_client: AsyncClient, spool):
|
|
await async_client.put(f"{INTERNAL}/{spool.id}/filament-presets", json=[_preset("H2C")])
|
|
|
|
response = await async_client.put(
|
|
f"{INTERNAL}/{spool.id}/filament-presets",
|
|
json=[_preset("X1C", "", "GFSA01"), _preset("X1C", "", "GFSA02")],
|
|
)
|
|
assert response.status_code == 422
|
|
|
|
# The rejected save must not have taken the existing override with it.
|
|
rows = (await async_client.get(f"{INTERNAL}/{spool.id}/filament-presets")).json()
|
|
assert [r["printer_model"] for r in rows] == ["H2C"]
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unknown_spool_is_404(self, async_client: AsyncClient):
|
|
response = await async_client.put(f"{INTERNAL}/999999/filament-presets", json=[_preset("H2C")])
|
|
assert response.status_code == 404
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_blank_model_is_rejected(self, async_client: AsyncClient, spool):
|
|
"""An empty printer_model would store a row the cascade can never
|
|
match, since it refuses to resolve without a model."""
|
|
response = await async_client.put(f"{INTERNAL}/{spool.id}/filament-presets", json=[_preset("")])
|
|
assert response.status_code == 422
|
|
|
|
|
|
@pytest.mark.integration
|
|
class TestSpoolmanInventory:
|
|
@pytest.mark.asyncio
|
|
async def test_empty_by_default(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
|
|
response = await async_client.get(f"{SPOOLMAN}/7/filament-presets")
|
|
assert response.status_code == 200
|
|
assert response.json() == []
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_put_then_get_round_trips(self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client):
|
|
response = await async_client.put(
|
|
f"{SPOOLMAN}/7/filament-presets",
|
|
json=[_preset("H2C"), _preset("H2C", "0.2", "GFSA10", "PLA @H2C 0.2 nozzle")],
|
|
)
|
|
assert response.status_code == 200, response.text
|
|
|
|
rows = (await async_client.get(f"{SPOOLMAN}/7/filament-presets")).json()
|
|
assert len(rows) == 2
|
|
assert all(r["spool_id"] == 7 for r in rows)
|
|
assert {r["nozzle_diameter"] for r in rows} == {"", "0.2"}
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_put_replaces_rather_than_appends(
|
|
self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
|
|
):
|
|
await async_client.put(f"{SPOOLMAN}/7/filament-presets", json=[_preset("H2C")])
|
|
await async_client.put(f"{SPOOLMAN}/7/filament-presets", json=[_preset("X1C")])
|
|
|
|
rows = (await async_client.get(f"{SPOOLMAN}/7/filament-presets")).json()
|
|
assert [r["printer_model"] for r in rows] == ["X1C"]
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_duplicate_key_is_rejected_without_losing_the_stored_rows(
|
|
self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
|
|
):
|
|
await async_client.put(f"{SPOOLMAN}/7/filament-presets", json=[_preset("H2C")])
|
|
|
|
response = await async_client.put(
|
|
f"{SPOOLMAN}/7/filament-presets",
|
|
json=[_preset("X1C", "", "GFSA01"), _preset("X1C", "", "GFSA02")],
|
|
)
|
|
assert response.status_code == 422
|
|
|
|
rows = (await async_client.get(f"{SPOOLMAN}/7/filament-presets")).json()
|
|
assert [r["printer_model"] for r in rows] == ["H2C"]
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_one_spools_overrides_do_not_leak_into_another(
|
|
self, async_client: AsyncClient, spoolman_settings, mock_spoolman_client
|
|
):
|
|
await async_client.put(f"{SPOOLMAN}/7/filament-presets", json=[_preset("H2C")])
|
|
assert (await async_client.get(f"{SPOOLMAN}/8/filament-presets")).json() == []
|